Reputation: 420
I'm not able make put request using ModelViewSet like in the documentation. My views, serializers are as below
class PostsViewSet(viewsets.ModelViewSet):
queryset = PostsModel.objects.all()
serializer_class = PostsSerializer
class PostsSerializer(serializers.ModelSerializer):
class Meta:
model=PostsModel
fields=('id','title', 'author', 'body')
PUT method is there in allowed methods as you can see in the picture.
And this is my posts.urls.py i.e., my app
router = DefaultRouter()
router.register('', PostsViewSet)
urlpatterns = [
path('', include(router.urls))
]
and this is my root urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('api/posts', include('posts.urls')),
]
and in response for
http://localhost:8000/api/posts/1/
Upvotes: 0
Views: 1274
Reputation: 1992
You are doing it right.
To see the PUT, PATCH and DELETE you need to access one specific entry. Because PUT, PATCH and DELETE are not bulk actions. So you should see PUT, DELETE when you access the endpoint /api/posts/1/
. In the response you should see,
HTTP 200 OK
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
Upvotes: 0
Reputation: 296
No need of trailing slash after id
change:
http://localhost:8000/api/posts/1/
to:
http://localhost:8000/api/posts/1
OR change URL pattern to:
path('api/posts/', include('posts.urls')),
and access the API using below url:
http://localhost:8000/api/posts/1/
Upvotes: 0
Reputation: 51988
I think the problem is here:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/posts', include('posts.urls')), # <-- Here
]
It should be:
path('api/posts/', include('posts.urls')), # need to append slash after posts
Here, there is nothing wrong with PUT
request, the problem is with routing itself. When you are hitting /posts/1
its not being found by django(because the configuration was not correct).
Upvotes: 1