Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding CreateAPIView, accessing request user

how can I save created_by as request user? Note that this field is not defined in the serializer

class User(models.Model):
    email = models.EmailField(...)
    name = models.CharField(...)
    created_by = models.ForeignKey('User')

class UserSerializer(serializer.ModelSerializer):
    class Meta:
        model = User
        fields = ['email', 'name']

class CreateUserApiView(CreateAPIView):
    model = User
    serializer_class = CreateRequesterSerializer

    def create(self, request, *args, **kwargs):
        # how can I save `created_by` as request user?
        return super(CreateUserApiView, self).create(request, *args, **kwargs)
like image 432
user3115655 Avatar asked Mar 06 '23 02:03

user3115655


1 Answers

Override the perform_create() method of CreateAPIView

class CreateUserApiView(CreateAPIView):
    # your code

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)
like image 111
JPG Avatar answered Mar 29 '23 07:03

JPG