I'm setting up a CRUD system with Django, using Class-Based Views. Currently I'm trying to figure out how to handle HTTP PUT and DELETE requests in my application. Despite searching the Django documentation extensively, I'm having trouble finding concrete examples and clear explanations of how to submit these types of queries to a class-based view.
I created a view class named CategoryView, extending from: django.views.View, in which I implemented the get and post methods successfully. And I want to build my urls like this:
- New Category: 127.0.0.1:8000/backendapp/categories/create
- List all Category: 127.0.0.1:8000/backendapp/categories/
- Retrieve only one Category: 127.0.0.1:8000/backendapp/categories/1
- Etc...
However, when I try to implement the put and delete methods, I get stuck.
For example :
from django.views import View
class CategoryView(View):
template_name = 'backendapp/pages/category/categories.html'
def get(self, request):
categories = Category.objects.all()
context = {
'categories': categories
}
return render(request, self.template_name, context)
def post(self, request):
return
def delete(self, request, pk):
return
def put(self, request):
return
I read through the Django documentation and found that Class-Based Views support HTTP requests: ["get", "post", "put", "patch", "delete", "head ", "options", "trace"].
link: https://docs.djangoproject.com/en/5.0/ref/class-based-views/base/#django.views.generic.base.View
Despite this, I can't figure out how to do it.
So I'm asking for your help to unblock me.
I looked at the Django documentation and searched online for examples and tutorials on handling HTTP requests in class-based views. I also tried experimenting with adding the put and delete methods to my CategoryView view class, but without success. I expected to find resources that clearly explain how to integrate these queries into my Django application, as well as practical examples demonstrating their use. However, I haven't found a working solution and am now seeking help from the community to overcome this difficulty.
<form method="delete">does not work, simply because the browser does not make a DELETE request.APIView, and therefore thus you might want to consider the Django REST API framework.