DEV Community

Mamadou762
Mamadou762

Posted on

How to effectively use PUT and DELETE HTTP methods in Django Class-Based Views?

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:

  1. New Category: 127.0.0.1:8000/backendapp/categories/create
  2. List all Category: 127.0.0.1:8000/backendapp/categories/
  3. Retrieve only one Category: 127.0.0.1:8000/backendapp/categories/1
  4. 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
Enter fullscreen mode Exit fullscreen mode

I read through the Django documentation and found that Class-Based Views support HTTP requests: ["get", "post", "put", "patch", "delete", "head ", "options", "trace"].
Link: Djando documentation

Despite this, I can't figure out how to do it.

So I'm asking for your help to unblock me.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay