Search code examples
pythondjangohttp-method

Django: URL to specific request method


I'm working with Django and I'M using class-based views with urls. So, in mu classes I have the methods: post, get, put and delete.

Example:

class MyClassView(View):
    def get(self, request, id=None):
        return HttpResponse('GET request')

    def post(self, request):
        return HttpResponse('POST request')

    def put(self, request, id):
        return HttpResponse('PUT request')

    def delete(self, request, id):
        return HttpResponse('DELETE request')

So in my URLs i have something like:

from django.urls import path
from . import views

urlpatterns =[
    path('my-class/', views.MyClassView.as_view()),
    path('my-class/<int:id>/', views.MyClassView.as_view()),
    path('my-class/create/', views.MyClassView.as_view()),
    path('my-class/update/<int:id>/', views.MyClassView.as_view()),
    path('my-class/delete/<int:id>/', views.MyClassView.as_view()),
]

This works fine! When I send a GET request to /my-class I get "GET request" and when a I send a POST request to /my-class/create I get "POST request" the same for others URLs.

The problem is, when I send a POST request to /my-class/ I get "POST request" and when I send a GET request to /my-class/creare I get "GET request"

I need the URL to work only for a specific request method. That is, url /my-class/create should only work for the POST method, url /my-class/update should only work for the PUT method and so on.

How can I do this? I've researched a lot, in the documentation and even right here but found no solution.


Solution

  • You can pass http_method_names directly to the .as_view() method. Tested on Django==3.2.3

    urlpatterns =[
        path('my-class/', views.MyClassView.as_view(http_method_names=['get'])),
        path('my-class/<int:id>/', views.MyClassView.as_view(http_method_names=['get'])),
        path('my-class/create/', views.MyClassView.as_view(http_method_names=['post'])),
        path('my-class/update/<int:id>/', views.MyClassView.as_view(http_method_names=['put'])),
        path('my-class/delete/<int:id>/', views.MyClassView.as_view(http_method_names=['delete'])),
    ]