DRF (1)


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.

<br />
class PostViewSet(viewsets.ModelViewSet):<br />
  queryset         = Post.objects.all()<br />
  serializer_class = serializers.PostSerializer</p>
<p>  def perform_create(self, serializer):<br />
    kwargs = {<br />
      'user': self.request.user # Change 'user' to you model user field.<br />
    }</p>
<p>    serializer.save(**kwargs)<br />

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

<br />
class UserCreateMixin(object):<br />
  &quot;&quot;&quot;<br />
  By default the user field is &quot;user&quot; you can change it<br />
  to your model &quot;user&quot; field.</p>
<p>  Usage:<br />
  class PostViewSet(UserCreateMixin, viewsets.ModelViewSet):<br />
    # ViewsSet required info...<br />
    user_field = 'creator'<br />
  &quot;&quot;&quot;<br />
  user_field = 'user'</p>
<p>  def get_user_field(self):<br />
    &quot;&quot;&quot;<br />
    You can dynamically change the user field<br />
    &quot;&quot;&quot;<br />
    return self.user_field</p>
<p>  def perform_create(self, serializer):<br />
    kwargs = {<br />
      self.get_user_field(): self.request.user<br />
    }</p>
<p>    serializer.save(**kwargs)<br />

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