How to correctly set Allow header for a HTTP_405_METHOD_NOT_ALLOWED status code in Django REST frameworkDjango REST Framework - 405 METHOD NOT ALLOWED using SimpleRouterDjango REST Framework: adding additional field to ModelSerializerHow can i correctly pass arguments to classbasedviews testing Django Rest Framework?How to expose non-model module methods via Django Rest Framework?Django Rest Framework Serializers and ViewsDjango REST Framework: Setting up prefetching for nested serializersDjango Rest Framework sets related serializer field to null on save for no reasonDjango REST Framework pagination links do not use HTTPSOverride accepted renderer in django-rest-framework on exceptionDjango Rest Framework batch requests

The eyes have it

How do governments keep track of their issued currency?

Was there a priest on the Titanic who stayed on the ship giving confession to as many as he could?

Is the term 'open source' a trademark?

Compiling c files on ubuntu and using the executable on Windows

How can I most clearly write a homebrew item that affects the ground below its radius after the initial explosion it creates?

What can plausibly explain many of my very long and low-tech bridges?

Why was the Sega Genesis marketed as a 16-bit console?

How to project 3d image in the planes xy, xz, yz?

Dual boot macOS Catalina 10.15 and macOS Mojave 10.14

What makes Ada the language of choice for the ISS's safety-critical systems?

Passing multiple files through stdin (over ssh)

What language is the software written in on the ISS?

Should an arbiter claim draw at a K+R vs K+R endgame?

Why would future John risk sending back a T-800 to save his younger self?

What is the `some` keyword in SwiftUI

Why did Canadian English remain so close to standard U.S English?

How to return a security deposit to a tenant

Genetic limitations to learn certain instruments

How is water heavier than petrol, even though its molecular weight is less than petrol?

When 2-pentene reacts with HBr, what will be the major product?

How did students remember what to practise between lessons without any sheet music?

Can a black dragonborn's acid breath weapon destroy objects?

Taxi Services at Didcot



How to correctly set Allow header for a HTTP_405_METHOD_NOT_ALLOWED status code in Django REST framework


Django REST Framework - 405 METHOD NOT ALLOWED using SimpleRouterDjango REST Framework: adding additional field to ModelSerializerHow can i correctly pass arguments to classbasedviews testing Django Rest Framework?How to expose non-model module methods via Django Rest Framework?Django Rest Framework Serializers and ViewsDjango REST Framework: Setting up prefetching for nested serializersDjango Rest Framework sets related serializer field to null on save for no reasonDjango REST Framework pagination links do not use HTTPSOverride accepted renderer in django-rest-framework on exceptionDjango Rest Framework batch requests






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'm currently looking to disable certain methods for an API endpoint - as added security. I'm using the status code that DRF suggests to use, that is for my case, "HTTP_405_METHOD_NOT_ALLOWED" - however, it looks to me that although this is working, the headers still say that the method is in Allow. See screenshot below:



HTTP_405_METHOD_NOT_ALLOWED Django Rest Framework example



As you can see, I am performing a GET request - but the Allow header is saying it's fine - even tho the status code is being applied correctly.



Stripped back example code:



class TokenValidateView(APIView):
def get(self, request, format=None):
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED, headers=?)


I believe I would need to set something in the headers dictionary (I've added ? where I'm not quite sure what needs to be done) as one of the arguments in the Response() function, but I'm not sure if this is a bug in DRF itself? Surely when that status code is passed it should be set in the headers accordingly?



N.B. I've also tried adding headers = 'Allow': 'POST' to the Response() argument, but that doesn't seem to work...










share|improve this question




























    1















    I'm currently looking to disable certain methods for an API endpoint - as added security. I'm using the status code that DRF suggests to use, that is for my case, "HTTP_405_METHOD_NOT_ALLOWED" - however, it looks to me that although this is working, the headers still say that the method is in Allow. See screenshot below:



    HTTP_405_METHOD_NOT_ALLOWED Django Rest Framework example



    As you can see, I am performing a GET request - but the Allow header is saying it's fine - even tho the status code is being applied correctly.



    Stripped back example code:



    class TokenValidateView(APIView):
    def get(self, request, format=None):
    return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED, headers=?)


    I believe I would need to set something in the headers dictionary (I've added ? where I'm not quite sure what needs to be done) as one of the arguments in the Response() function, but I'm not sure if this is a bug in DRF itself? Surely when that status code is passed it should be set in the headers accordingly?



    N.B. I've also tried adding headers = 'Allow': 'POST' to the Response() argument, but that doesn't seem to work...










    share|improve this question
























      1












      1








      1








      I'm currently looking to disable certain methods for an API endpoint - as added security. I'm using the status code that DRF suggests to use, that is for my case, "HTTP_405_METHOD_NOT_ALLOWED" - however, it looks to me that although this is working, the headers still say that the method is in Allow. See screenshot below:



      HTTP_405_METHOD_NOT_ALLOWED Django Rest Framework example



      As you can see, I am performing a GET request - but the Allow header is saying it's fine - even tho the status code is being applied correctly.



      Stripped back example code:



      class TokenValidateView(APIView):
      def get(self, request, format=None):
      return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED, headers=?)


      I believe I would need to set something in the headers dictionary (I've added ? where I'm not quite sure what needs to be done) as one of the arguments in the Response() function, but I'm not sure if this is a bug in DRF itself? Surely when that status code is passed it should be set in the headers accordingly?



      N.B. I've also tried adding headers = 'Allow': 'POST' to the Response() argument, but that doesn't seem to work...










      share|improve this question














      I'm currently looking to disable certain methods for an API endpoint - as added security. I'm using the status code that DRF suggests to use, that is for my case, "HTTP_405_METHOD_NOT_ALLOWED" - however, it looks to me that although this is working, the headers still say that the method is in Allow. See screenshot below:



      HTTP_405_METHOD_NOT_ALLOWED Django Rest Framework example



      As you can see, I am performing a GET request - but the Allow header is saying it's fine - even tho the status code is being applied correctly.



      Stripped back example code:



      class TokenValidateView(APIView):
      def get(self, request, format=None):
      return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED, headers=?)


      I believe I would need to set something in the headers dictionary (I've added ? where I'm not quite sure what needs to be done) as one of the arguments in the Response() function, but I'm not sure if this is a bug in DRF itself? Surely when that status code is passed it should be set in the headers accordingly?



      N.B. I've also tried adding headers = 'Allow': 'POST' to the Response() argument, but that doesn't seem to work...







      django django-rest-framework django-class-based-views






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 16:21









      Wind Up Lord VexxosWind Up Lord Vexxos

      729




      729






















          3 Answers
          3






          active

          oldest

          votes


















          0














          When you override the get method of the view,GET is automatically added to the Allow header by django-rest-framework, no matter what Response you return. You can simply remove get method if you want it to return 405 Not Allowed.



          If for a reason, you want to keep get method and do not include GET in to the Allow header, you can override allowed_methods property in your view:



          @property
          def allowed_methods(self):
          allowed_methods = super().allowed_methods
          allowed_methods.remove('GET')
          return allowed_methods





          share|improve this answer






























            0














            Since you are using the APIView class, it will allow all the methods which are defined in your view class. The DRF response allowed the HTTP GET method because you'd defined in on your view.




            The below view class will allow HTTP GET,HTTP POST,HTTP PATCH,HTTP PUT and HTTP DELETE



            class TokenValidateView(APIView):
            def get(self, request, format=None):
            # something
            return Response("this is HTTP GET")

            def post(self, request, format=None):
            return Response("this is HTTP POST")

            def patch(self, request, format=None):
            return Response("this is HTTP PATCH")

            def put(self, request, format=None):
            return Response("this is HTTP PUT")

            def delete(self, request, format=None):
            return Response("this is HTTP DELETE")


            As I said above, the response class checks the http methods inside the view class, not their responses.


            So, If you want to remove the HTTP GET method from your Allowed Methods, just remove the get() method from the view class



            class TokenValidateView(APIView):
            # remove the "get()" method
            def get(self, request, format=None):
            # something
            return Response("this is HTTP GET")

            def post(self, request, format=None):
            return Response("this is HTTP POST")

            def patch(self, request, format=None):
            return Response("this is HTTP PATCH")

            def put(self, request, format=None):
            return Response("this is HTTP PUT")

            def delete(self, request, format=None):
            return Response("this is HTTP DELETE")





            share|improve this answer






























              0














              If you don't need the method just don't implement it on view which is subclassing ApiView. It will automatically send the method not allowed response.






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325899%2fhow-to-correctly-set-allow-header-for-a-http-405-method-not-allowed-status-code%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                0














                When you override the get method of the view,GET is automatically added to the Allow header by django-rest-framework, no matter what Response you return. You can simply remove get method if you want it to return 405 Not Allowed.



                If for a reason, you want to keep get method and do not include GET in to the Allow header, you can override allowed_methods property in your view:



                @property
                def allowed_methods(self):
                allowed_methods = super().allowed_methods
                allowed_methods.remove('GET')
                return allowed_methods





                share|improve this answer



























                  0














                  When you override the get method of the view,GET is automatically added to the Allow header by django-rest-framework, no matter what Response you return. You can simply remove get method if you want it to return 405 Not Allowed.



                  If for a reason, you want to keep get method and do not include GET in to the Allow header, you can override allowed_methods property in your view:



                  @property
                  def allowed_methods(self):
                  allowed_methods = super().allowed_methods
                  allowed_methods.remove('GET')
                  return allowed_methods





                  share|improve this answer

























                    0












                    0








                    0







                    When you override the get method of the view,GET is automatically added to the Allow header by django-rest-framework, no matter what Response you return. You can simply remove get method if you want it to return 405 Not Allowed.



                    If for a reason, you want to keep get method and do not include GET in to the Allow header, you can override allowed_methods property in your view:



                    @property
                    def allowed_methods(self):
                    allowed_methods = super().allowed_methods
                    allowed_methods.remove('GET')
                    return allowed_methods





                    share|improve this answer













                    When you override the get method of the view,GET is automatically added to the Allow header by django-rest-framework, no matter what Response you return. You can simply remove get method if you want it to return 405 Not Allowed.



                    If for a reason, you want to keep get method and do not include GET in to the Allow header, you can override allowed_methods property in your view:



                    @property
                    def allowed_methods(self):
                    allowed_methods = super().allowed_methods
                    allowed_methods.remove('GET')
                    return allowed_methods






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 24 at 20:32









                    zeynelzeynel

                    620312




                    620312























                        0














                        Since you are using the APIView class, it will allow all the methods which are defined in your view class. The DRF response allowed the HTTP GET method because you'd defined in on your view.




                        The below view class will allow HTTP GET,HTTP POST,HTTP PATCH,HTTP PUT and HTTP DELETE



                        class TokenValidateView(APIView):
                        def get(self, request, format=None):
                        # something
                        return Response("this is HTTP GET")

                        def post(self, request, format=None):
                        return Response("this is HTTP POST")

                        def patch(self, request, format=None):
                        return Response("this is HTTP PATCH")

                        def put(self, request, format=None):
                        return Response("this is HTTP PUT")

                        def delete(self, request, format=None):
                        return Response("this is HTTP DELETE")


                        As I said above, the response class checks the http methods inside the view class, not their responses.


                        So, If you want to remove the HTTP GET method from your Allowed Methods, just remove the get() method from the view class



                        class TokenValidateView(APIView):
                        # remove the "get()" method
                        def get(self, request, format=None):
                        # something
                        return Response("this is HTTP GET")

                        def post(self, request, format=None):
                        return Response("this is HTTP POST")

                        def patch(self, request, format=None):
                        return Response("this is HTTP PATCH")

                        def put(self, request, format=None):
                        return Response("this is HTTP PUT")

                        def delete(self, request, format=None):
                        return Response("this is HTTP DELETE")





                        share|improve this answer



























                          0














                          Since you are using the APIView class, it will allow all the methods which are defined in your view class. The DRF response allowed the HTTP GET method because you'd defined in on your view.




                          The below view class will allow HTTP GET,HTTP POST,HTTP PATCH,HTTP PUT and HTTP DELETE



                          class TokenValidateView(APIView):
                          def get(self, request, format=None):
                          # something
                          return Response("this is HTTP GET")

                          def post(self, request, format=None):
                          return Response("this is HTTP POST")

                          def patch(self, request, format=None):
                          return Response("this is HTTP PATCH")

                          def put(self, request, format=None):
                          return Response("this is HTTP PUT")

                          def delete(self, request, format=None):
                          return Response("this is HTTP DELETE")


                          As I said above, the response class checks the http methods inside the view class, not their responses.


                          So, If you want to remove the HTTP GET method from your Allowed Methods, just remove the get() method from the view class



                          class TokenValidateView(APIView):
                          # remove the "get()" method
                          def get(self, request, format=None):
                          # something
                          return Response("this is HTTP GET")

                          def post(self, request, format=None):
                          return Response("this is HTTP POST")

                          def patch(self, request, format=None):
                          return Response("this is HTTP PATCH")

                          def put(self, request, format=None):
                          return Response("this is HTTP PUT")

                          def delete(self, request, format=None):
                          return Response("this is HTTP DELETE")





                          share|improve this answer

























                            0












                            0








                            0







                            Since you are using the APIView class, it will allow all the methods which are defined in your view class. The DRF response allowed the HTTP GET method because you'd defined in on your view.




                            The below view class will allow HTTP GET,HTTP POST,HTTP PATCH,HTTP PUT and HTTP DELETE



                            class TokenValidateView(APIView):
                            def get(self, request, format=None):
                            # something
                            return Response("this is HTTP GET")

                            def post(self, request, format=None):
                            return Response("this is HTTP POST")

                            def patch(self, request, format=None):
                            return Response("this is HTTP PATCH")

                            def put(self, request, format=None):
                            return Response("this is HTTP PUT")

                            def delete(self, request, format=None):
                            return Response("this is HTTP DELETE")


                            As I said above, the response class checks the http methods inside the view class, not their responses.


                            So, If you want to remove the HTTP GET method from your Allowed Methods, just remove the get() method from the view class



                            class TokenValidateView(APIView):
                            # remove the "get()" method
                            def get(self, request, format=None):
                            # something
                            return Response("this is HTTP GET")

                            def post(self, request, format=None):
                            return Response("this is HTTP POST")

                            def patch(self, request, format=None):
                            return Response("this is HTTP PATCH")

                            def put(self, request, format=None):
                            return Response("this is HTTP PUT")

                            def delete(self, request, format=None):
                            return Response("this is HTTP DELETE")





                            share|improve this answer













                            Since you are using the APIView class, it will allow all the methods which are defined in your view class. The DRF response allowed the HTTP GET method because you'd defined in on your view.




                            The below view class will allow HTTP GET,HTTP POST,HTTP PATCH,HTTP PUT and HTTP DELETE



                            class TokenValidateView(APIView):
                            def get(self, request, format=None):
                            # something
                            return Response("this is HTTP GET")

                            def post(self, request, format=None):
                            return Response("this is HTTP POST")

                            def patch(self, request, format=None):
                            return Response("this is HTTP PATCH")

                            def put(self, request, format=None):
                            return Response("this is HTTP PUT")

                            def delete(self, request, format=None):
                            return Response("this is HTTP DELETE")


                            As I said above, the response class checks the http methods inside the view class, not their responses.


                            So, If you want to remove the HTTP GET method from your Allowed Methods, just remove the get() method from the view class



                            class TokenValidateView(APIView):
                            # remove the "get()" method
                            def get(self, request, format=None):
                            # something
                            return Response("this is HTTP GET")

                            def post(self, request, format=None):
                            return Response("this is HTTP POST")

                            def patch(self, request, format=None):
                            return Response("this is HTTP PATCH")

                            def put(self, request, format=None):
                            return Response("this is HTTP PUT")

                            def delete(self, request, format=None):
                            return Response("this is HTTP DELETE")






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 25 at 4:24









                            JPGJPG

                            20.1k31141




                            20.1k31141





















                                0














                                If you don't need the method just don't implement it on view which is subclassing ApiView. It will automatically send the method not allowed response.






                                share|improve this answer



























                                  0














                                  If you don't need the method just don't implement it on view which is subclassing ApiView. It will automatically send the method not allowed response.






                                  share|improve this answer

























                                    0












                                    0








                                    0







                                    If you don't need the method just don't implement it on view which is subclassing ApiView. It will automatically send the method not allowed response.






                                    share|improve this answer













                                    If you don't need the method just don't implement it on view which is subclassing ApiView. It will automatically send the method not allowed response.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Mar 25 at 4:32









                                    samsam

                                    435514




                                    435514



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55325899%2fhow-to-correctly-set-allow-header-for-a-http-405-method-not-allowed-status-code%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                        SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                        은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현