Search code examples
pythondjangodjango-rest-frameworkputpostman

Unable to do PUT operation -DjangoRESTFramework


I am unable to do PUT operation in Django rest framework, I am able to GET, POST, DELETE operation.

This is the error Image I have tried using @api_view but there also its not, I mostly refer the djangorestframework website

Below is my code:

serializers.py

from rest_framework import serializers
from snippets.models import Snippet
#from django.contrib.auth.models import *

class SnippetSerializer(serializers.ModelSerializer):
            class Meta:
                model = Snippet
                fields = ('id','title','code')

Models.py

from __future__ import unicode_literals
from django.db import models

# Create your models here.


class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.CharField(max_length=100, blank=True, default='')


class Meta:
    ordering = ('created',)

Views.py

from rest_framework import viewsets
from rest_framework.decorators import api_view
from snippets.serializers import SnippetSerializer

    class SnippetViewSet(viewsets.ModelViewSet):
        """
        API endpoint that allows users to be viewed or edited.
        """
        queryset = Snippet.objects.all().order_by('id')
        serializer_class = SnippetSerializer

urls.py

rom django.conf.urls import url, include
from rest_framework import routers
from django.contrib import admin
from snippets import views




router = routers.DefaultRouter()
router.register(r'snippet', views.SnippetViewSet)


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),

]

Solution

  • Looking at the documentation of DefaultRouter, it looks like that PUT method can only be used with {basename}-detail type of URLs.

    While you are using it directly on /snippet url where it is not allowed.