Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

How to assign a logged in user automatically to a post In Django Rest framework?


I have created a model to post an ad. Since the CreateApiView is protected so that only logged in user can create or post ad, but if the logged in user posts an ad how to automatically take the logged user name or assign that user to his ad?

This is what I have tried in my viewsets

def perform_create(self, serializer):
    return serializer.save(owner=self.request.user)

this is my models.py

class Add(models.Model):
CATEGORY_CHOICES = (
    (1, 'Khashi'),
    (2, 'Boka'),
    (3, 'Goat'),
    (4, 'Chyangra'),
    (5, 'Veda'),
)
user = models.ForeignKey(User, on_delete = models.CASCADE)
title = models.CharField(("Title"), max_length=50)
category = models.IntegerField(("Choose Category"), choices=CATEGORY_CHOICES)
Short_discription = models.CharField(("Short Discription"), max_length=200)

this is my serializers.py

class KhashiSerializer(serializers.ModelSerializer):
    class Meta:
        model = Add
        fields = '__all__'
        read_only_fields = ['user']

this is my viewset

class KhashiCreateApiView(generics.CreateAPIView):
    queryset = Add.objects.all()
    serializer_class = KhashiSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

I'm getting this error with this endpoint http://127.0.0.1:8000/api/khashi/khashi_add

OperationalError at /api/khashi/khashi_add
table add_khashi_add has no column named user_id

Is there any way to assign user to the post so that if POST reqest in Postman without user provided will automatically assign logged in user or user with Token that is provided in Authorization header??


Solution

  • Okay I figure it out by myself.... I just update my serializers.py using validate method

    class KhashiSerializer(serializers.ModelSerializer):
    class Meta:
        model = Add
        fields = '__all__'
        read_only_fields = ['user']
    
    def validate(self, attrs):
        attrs['user'] = self.context['request'].user
        return attrs