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.

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.




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.

export PIP_REQUIRE_VIRTUALENV=true
# define a "global pip" function to use outside virtualenv:
gpip(){
    PIP_REQUIRE_VIRTUALENV="" pip "$@"
}

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