Error when checking owner in REST API CreateAPIView

798 views
Skip to first unread message

Daniel Grace

unread,
Jul 9, 2015, 5:44:33 PM7/9/15
to django...@googlegroups.com
With CreateAPIView from the REST API I am trying to stop users from creating data in another users name.

In models.py:
class UserData(models.Model):
    user = models.OneToOneField(User, db_index=True, related_name='userdata', blank=False, null=False)
    textdata = models.TextField(blank=True, null=True)

In views.py:
class UserDataCreateView(generics.CreateAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = UserDataSerializer
    queryset = UserData.objects.all()
    def create(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.user != request.user:
            raise PermissionDenied
        return super(UserDataCreateView, self).create(request, *args, **kwargs)

Gives the error:
Expected view UserDataCreateView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

What am I doing wrong?  Alternatively, how would I set the user ID on the newly created record without saving twice (which would not be a good idea) ?

Carlton Gibson

unread,
Jul 9, 2015, 8:16:56 PM7/9/15
to django...@googlegroups.com
Hi Daniel,

The call to get_object won't work, since Create views don't yet have an object to fetch.

The correct approach is override perform_create and pass the user to your serialiser's save method.

There's a section in the tutorial that covers this exact use case:


Check it out. Hopefully that helps.

Also you may find more luck with DRF related questions on the DRF mailing list itself: 


Kind Regards, Carlton 





--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/58f8053e-c13e-4d45-b480-e6b53abb1ea4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

James Schneider

unread,
Jul 9, 2015, 8:30:09 PM7/9/15
to django...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages