Django Rest Framework auto assign current user on creation

If you use the ModelViewSet provided by Django Rest Framework you overwrite the perform_create method on the ModelViewSet to auto set the current user to the model before saving.

class PostViewSet(viewsets.ModelViewSet):
  queryset         = Post.objects.all()
  serializer_class = serializers.PostSerializer

  def perform_create(self, serializer):
    kwargs = {
      'user': self.request.user # Change 'user' to you model user field.
    }

    serializer.save(**kwargs)

As usual my recommendation is to create “Mixin” like this one:

class UserCreateMixin(object):
  """
  By default the user field is "user" you can change it
  to your model "user" field.

  Usage:
  class PostViewSet(UserCreateMixin, viewsets.ModelViewSet):
    # ViewsSet required info...
    user_field = 'creator'
  """
  user_field = 'user'

  def get_user_field(self):
    """
    You can dynamically change the user field
    """
    return self.user_field

  def perform_create(self, serializer):
    kwargs = {
      self.get_user_field(): self.request.user
    }

    serializer.save(**kwargs)

If you think that there is a better way, let us know in the comments bellow.




Irving Kcam

Full Stack Developer. AWS lover, Django ninja, Angular enthusiast.

No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *