3👍
✅
To send extra context data you should pass it from the method def get_serializer_context(self)
and access inside serializer like self.context.get("key")
.
sample code:
class GroupListView(ListCreateAPIView):
queryset = Group.objects.all()
def get_serializer_context(self):
context = super(GroupListView, self).get_serializer_context()
context["users_to_invite"] = request.data.get("users_to_invite")
return context
class GroupCreateSerializer(ModelSerializer):
def create(self, validated_data):
users_to_invite = self.context.get("users_to_invite")
# do whatever you want
6👍
extra data is absent in validated_data
you can try use self.context['request']
details: including-extra-context, by default it added in the get_serializer method of view
for your case:
def create(self, validated_data):
# Get user ids to invite
# !! It fails here !!
request = self.context['request']
invitations_data = request.data.get('users_to_invite')
- [Django]-How to display multi-word app names properly (i.e. with spaces) in Django admin?
- [Django]-Is there a reason I should be dissuaded from using an alternative templating engine in my Django app?
- [Django]-Looking for read-write lock in Django using PostgreSQL, e.g., SELECT FOR SHARE
- [Django]-'Member' object has no attribute 'all'
- [Django]-Multi-table inheritance in the admin view
0👍
Apart from adding the data to context, you can add the field users_to_invite
to serializer as a CharField
.
Example:
import json
class GroupCreateSerializer(ModelSerializer):
def create(self, validated_data):
# Get user ids to invite
# !! It fails here !!
invitations_data = json.loads(validated_data.pop('users_to_invite'))
# TODO: Iterate over ids and create invitations
# Create a group
group = Group.objects.create(**validated_data)
return group
users_to_invite = serializers.CharField(required=False)
class Meta:
model = Group
fields = ('id', 'name', 'users_to_invite', )
Note: Make sure to have users_to_invite
in request data as a string. Like: '[1, 2, 3]'
Source:stackexchange.com