Django Rest Framework: Disable field update after object is created

It seems that you need different serializers for POST and PUT methods. In the serializer for PUT method you are able to just except the username field (or set the username field as read only). class UserViewSet(viewsets.ModelViewSet): “”” API endpoint that allows users to be viewed or edited. “”” serializer_class = UserSerializer model = User … Read more

Pass request context to serializer from Viewset in Django Rest Framework

GenericViewSet has the get_serializer_context method which will let you update context: class MyModelViewSet(ModelViewSet): queryset = MyModel.objects.all() permission_classes = [DjangoModelPermissions] serializer_class = MyModelSerializer def get_serializer_context(self): context = super().get_serializer_context() context.update({“request”: self.request}) return context For Python 2.7, use context = super(MyModelViewSet, self).get_serializer_context()

What’s the appropriate HTTP status code to return if a user tries logging in with an incorrect username / password, but correct format?

If you are strictly using the HTTP authentication framework provided by RFC 7235 for your REST API, the correct HTTP code would actually be 401. From the RFC: The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a … Read more

How do you filter a nested serializer in Django Rest Framework?

You can subclass the ListSerializer and overwrite the to_representation method. By default the to_representation method calls data.all() on the nested queryset. So you effectively need to make data = data.filter(**your_filters) before the method is called. Then you need to add your subclassed ListSerializer as the list_serializer_class on the meta of the nested serializer. subclass ListSerializer, … Read more

Order of Serializer Validation in Django REST Framework

Since most likely your username field has unique=True set, Django REST Framework automatically adds a validator that checks to make sure the new username is unique. You can actually confirm this by doing repr(serializer()), which will show you all of the automatically generated fields, which includes the validators. Validation is run in a specific, undocumented … Read more

AngularJS + Django Rest Framework + CORS ( CSRF Cookie not showing up in client )

AngularJS Single Page Web Application on Sub-domain A, talking to a Django JSON (REST) API on Sub-domain B using CORS and CSRF protection Since I’m currently working on a similar setup and was battling to get CORS to work properly in combination with CSRF protection, I wanted to share my own learnings here. Setup – … Read more