Python (2)


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.




Require activated virtualenv on PIP

I highly recommended to separate your working environments so every project has their own set of packages. To do this just edit the ~/.bash_profile file.

<br />
export PIP_REQUIRE_VIRTUALENV=true<br />
# define a &quot;global pip&quot; function to use outside virtualenv:<br />
gpip(){<br />
    PIP_REQUIRE_VIRTUALENV=&quot;&quot; pip &quot;$@&quot;<br />
}<br />

After that, reload the source file with this command source ~/.bash_profile.