Home > OS >  How to get the authentificated user information in Model Serializer in Django Rest?
How to get the authentificated user information in Model Serializer in Django Rest?

Time:02-21

I have a LinkList object, which has owner property - the username of the User it belongs to. I am trying to have LinkLists be linked to the user that made the create request, however self.context['request'].user and CurrentUserDefault don't work in my create method, so I cannot create an instance of the LinkList object.

The error I am getting:

NOT NULL constraint failed: llists_linklist.owner_id

Here is the serializer:

class LinkListSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name="lists-detail")
    owner = serializers.ReadOnlyField(source='owner.username')
    links = LinkSerializer(many=True)

    class Meta:
        model = LinkList
        fields = ['url', 'owner', 'name', 'public', 'links']

    def create(self, validated_data):
        links = validated_data.pop('links', [])
        instance = super().create(validated_data)
        for item in links:
            instance.links.add(link=item)
        return instance

The model:

class LinkList(models.Model):
    owner = models.ForeignKey(
        User,
        related_name='lists',
        on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=250)
    public = models.BooleanField(default=False)
    links = models.ManyToManyField(
        Link,
        related_name='linklists')

    def __str__(self):
        return "%s - %s" % (self.owner, self.name)

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

CodePudding user response:

The problem is, the owner field is actually a required field and you are not passing it through the serializer as you made the owner field in the serializer read only.

Looks like you have two options:

1. You do not need the owner field to be returned

If so, just use the HiddenField() with CurrentUserDefault():

owner = serializers.HiddenField(default=serializers.CurrentUserDefault())

2. You need the owner field to be returned

If so, just pass the user manually to the serializer's save() method in the view's perform_create() method (I assume you are using generic view):

serializer.save(owner=self.request.user)

  • Related