Last active
June 20, 2016 23:13
-
-
Save ezheidtmann/8e9dd874cd0a788d8d3b to your computer and use it in GitHub Desktop.
How to enable "PUT to create" with Django Rest Framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from rest_framework import viewsets | |
from django.http import Http404 | |
class MyViewSet(viewsets.ModelViewSet): | |
serializer_class = MySerializer | |
# ... | |
def update(self, request, *args, **kwargs): | |
partial = kwargs.get('partial', False) | |
try: | |
return super(MyViewSet, self).update(request, *args, **kwargs) | |
except Http404: | |
if partial: | |
raise | |
# Allow PUT to create | |
return super(MyViewSet, self).create(request, *args, **kwargs) | |
def perform_create(self, serializer): | |
save_kwargs = { | |
# You may add other implicit fields here, such as client app version | |
'owner': self.request.user, | |
} | |
# Allow PUT to create: if this is a PUT, we'll get the primary key in | |
# the URL kwargs. | |
# | |
# If you're using some other url-kwargs or are indexing models by some | |
# other key, then adapt this logic to match. | |
if 'pk' in self.kwargs: | |
save_kwargs['pk'] = self.kwargs['pk'] | |
serializer.save(**save_kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment