How to programmatically provide `queryset` to PrimaryKeyRelatedField in DRF 3

The key is to subclass PrimaryKeyRelatedField and overload the get_queryset method, using the user information from the request context: class UserFilteredPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def get_queryset(self): request = self.context.get(‘request’, None) queryset = super(UserFilteredPrimaryKeyRelatedField, self).get_queryset() if not request or not queryset: return None return queryset.filter(user=request.user) You can then use this new serializer just like the (unfiltered) original: class MySerializer(serializers.ModelSerializer): … Read more

Django Rest Framework Nested Serializer required=False error

Ok, so Kevin Browns comment is correct. I needed to add allow_null=True. class SerializerA(serializers.Serializer): details = DetailsSerializer(required=False, allow_null=True) The reason for this is that having required=False allows the field details to be absent from the data when constructing the serializer. e.g. s = SerializerA(data={}) whereas allow_null permits the the param to be specified but be … Read more

How to dynamically remove fields from serializer output

You can customize the serialization behavior by overriding the to_representation() method in your serializer. class DynamicSerliazer(serializers.ModelSerializer): def to_representation(self, obj): # get the original representation ret = super(DynamicSerializer, self).to_representation(obj) # remove ‘url’ field if mobile request if is_mobile_platform(self.context.get(‘request’, None)): ret.pop(‘url’) # here write the logic to check whether `elements` field is to be removed # pop … Read more

Django REST framework: Check user is in group

The sensible way to parameterize permission classes is to put the parameters on the view class. That’ll let you change the behaviour from view to view. Here’s an example: # permissions.py from django.contrib.auth.models import Group from rest_framework import permissions def is_in_group(user, group_name): “”” Takes a user and a group name, and returns `True` if the … Read more

django-rest-framework accept JSON data?

You have missed adding the Content-Type header in the headers section. Just set the Content-Type header to application/json and it should work. See the below image: Also, you might also need to include a CSRF token in the header in case you get an error {“detail”: “CSRF Failed: CSRF token missing or incorrect.”} while making … Read more

Using Django Rest Framework’s browsable API with APIViews?

To mix with routers and APIView classes or method based in such a way that the API Root displays both with minimal code views in the APIRoot view I wrote a custom router that extends DefaultRouter and overrides get_urls and get_api_root_view; it looks like as follows : from rest_framework import routers, views, reverse, response class … Read more

How do you authenticate a websocket with token authentication on django channels?

For Django-Channels 2 you can write custom authentication middleware https://gist.github.com/rluts/22e05ed8f53f97bdd02eafdf38f3d60a token_auth.py: from channels.auth import AuthMiddlewareStack from rest_framework.authtoken.models import Token from django.contrib.auth.models import AnonymousUser class TokenAuthMiddleware: “”” Token authorization middleware for Django Channels 2 “”” def __init__(self, inner): self.inner = inner def __call__(self, scope): headers = dict(scope[‘headers’]) if b’authorization’ in headers: try: token_name, token_key = headers[b’authorization’].decode().split() … Read more

ForeignKey does not allow null values

The blank option is used in the form validation, and the null is used when writing to database. So you might add null=True to that field. EDIT: continue the comment Considering the two steps when saving object: Validator(controlled by blank) Database limitation(controlled by null) For default option, take IntegerField for example, default=5, blank=True, null=False, pass … Read more