16

Using django-rest-framework 3 and django 1.8

I am trying to create a user using django-rest-framework ModelViewSerializer. problem is that the default objects.create method used by DRF leave the password as plain text.

The problem is that DRF serialzer create method is using objects.create querysets/#create method instead of using objects.create_user method.

code from serializers.py line 775

instance = ModelClass.objects.create(**validated_data)

What is the best solution for this? i can override the serializer.create method to use objects.user_create instead of objects.create but it does not feel like the right solution.

rest of code:

from django.contrib.auth.models import User
from rest_framework import viewsets

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'email','password')
        write_only_fields = ('password',)


class UserViewSet(viewsets.ModelViewSet):   
    queryset = User.objects.all()
    serializer = UserSerializer()
2
  • 3
    Why doesn't it seem right to you? I think I would go that way. Searched a bit and at least found this SO post (different question), but overriding create() is used for that purpose in the accepted answer. stackoverflow.com/a/27763502/870769
    – sthzg
    Commented Apr 20, 2015 at 12:47
  • The write_only_fields argument is not used anymore. Instead, extra_kwargs = {'password': {'write_only': True}} should be used in the Meta-class docs Commented Dec 14, 2022 at 14:33

4 Answers 4

22

you can override create in UserSerializer:

class UserSerializer(serializers.ModelSerializer):
    # ....

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user

other solutions can be overriding perform_create in ViewSet class or you can write your own create method in your viewset class

class UserViewSet(viewsets.ModelViewSet): 
    def create(self, request, format=None):
        # create user here
        # do not call seriailzer.save()

UPDATE: after @freethebees commented, overriding perform_create also works, so here is the code snippet:

class UserViewSet(viewsets.ModelViewSet, mixins.CreateModelMixin): 
    def perform_create(self, serializer):
        # use User.objects.create_user to create user
        pass

NOTE: this answer gives 3 solutions, choose the one you think it better fits your needs and your project's ecosystem

NOTE 2 I personally prefer overriding create in UserViewSet (second code snippet) because there you can simply return your custom Response (for example return user profile after login)

5
  • Why would you recommend overriding the create method in a serialiser rather than perform_create in a ViewSet? Commented Dec 9, 2016 at 15:22
  • @freethebees it's an old answer, I don't remember why :-), but you are right perform_create seems to be cleaner solution, I'll update my answer.
    – aliva
    Commented Dec 10, 2016 at 9:55
  • Oh I wasn't suggesting either way was better. I was just interested. I haven't seen where either method would be the clear choice. Commented Dec 10, 2016 at 16:06
  • Instead of using User.objects.create_user, could you just use the make_password function from django.contrib.auth.hashers? So, inside of perform_create you would have two lines: serializer.validated_data['password'] = make_password(serializer.validated_data['password']) and serializer.save()
    – Nick
    Commented Jan 17, 2017 at 23:14
  • @Nick for your solution I think you only need to update validate_password in serializer and it should work. (but I personally don't like it, 1. using create_user is recommended in django docs (think about custom user models and you should do all create_user stuffs in your serializer, update same code in 2 places) 2. I prefer explicit solution (i think your solution makes code a little harder to understand))
    – aliva
    Commented Jan 18, 2017 at 20:05
11

In addition to @aliva's answer where you miss out on the functionalities in serializers.Modelserializer.create() (which could be quite nice to preserve, for example handling of many-to-many relations), there is a way to keep this.

By using the user.set_password() method, the password can also be correctly set, like:

class UserSerializer(serializers.ModelSerializer):

    def create(self, validated_data):
        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

This has the benefit of keeping the super class' functionality, but the downside of an additional write to the database. Decide which trade-off is more important to you :-).

See documentation for set_password.

5
  • This worked for me! I can't understand why other suggested approaches to this question did not work.
    – manpikin
    Commented Feb 10, 2019 at 16:46
  • 1
    The reason no one else has suggested this, is that it will save the raw user password to the database which is a huge anti-pattern. Even if it lives in the database for only 1ms, it could live in logs forever.
    – jkatzer
    Commented May 14, 2020 at 19:17
  • @jkatzer : set_password() hashes the password. Is it still a problem?
    – Aurélien
    Commented Apr 1, 2021 at 12:41
  • @Aurélien True, here's the documentation which confirms this: docs.djangoproject.com/en/3.1/topics/auth/customizing/…
    – Erikw
    Commented Apr 1, 2021 at 18:39
  • @Erikw Indeed, I was aware of this, so this is not a n "anti-pattern" practice, isn't it?
    – Aurélien
    Commented Apr 1, 2021 at 19:06
9

There is even better option to validate password in serializer

from django.contrib.auth.hashers import make_password

class UserSerializer(serializers.ModelSerializer):
    def validate_password(self, value: str) -> str:
        return make_password(value)
3
  • This has the added benefit of also applying to updates, if that's something your view supports.
    – Ben
    Commented Apr 12, 2018 at 4:04
  • return validate_password(value) works better here, Django 3.2.2
    – Lucas
    Commented May 11, 2021 at 9:06
  • The value of validated_data['password'] in serializer.create method has the same old value, do you have any idea?
    – Mu Sa
    Commented Jul 30, 2021 at 11:48
3

A complete example that support POST and PUT/PATCH without another SQL UPDATE statement.

class MyUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = '__all__'

    def create(self, validated_data):
        if "password" in validated_data:
            from django.contrib.auth.hashers import make_password
            validated_data["password"] = make_password(validated_data["password"])
        return super().create(validated_data)

    def update(self, instance, validated_data):
        if "password" in validated_data:
            from django.contrib.auth.hashers import make_password
            validated_data["password"] = make_password(validated_data["password"])
        return super().update(instance, validated_data)
1
  • Great, thank you. After searching for ages I didn't realise that Django was hashing passwords causing all my sign in attempts to fail.
    – jigglypuff
    Commented Jan 25, 2022 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.