Naveen
Naveen

Reputation: 852

How to change the data before .create is called in django rest

I have this following model

class User(models.Model):
    UserName = models.CharField(max_length=20)
    Password = models.CharField(max_length=255)
    RoleName = models.CharField(max_length=30)
    Email = models.EmailField(max_length=50)
    ApartmentName = models.CharField(max_length=50)
    UserId = models.BigAutoField(primary_key=True)

I have saved the data by calling this view

class Register(generics.CreateAPIView):

    serializer_class = serializers.UserSerializer
    def get_queryset(self, *args, **kwargs):
        return models.User.objects.all()

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

But before the row to be created in the database table i need to change the password to the hashed form, i cant alter the post variables in the request since it is immutable.How to hash the password with make_password before saving the data?

Upvotes: 1

Views: 2129

Answers (2)

Lucas Weyne
Lucas Weyne

Reputation: 1152

If the User objects are created only from Register view, override the create method of UserSerializer works fine. However, users created through others ways (admin interface, django form, management command, etc.) will not have their passwords encrypted unless you provide some code to do so in all of theese ways.

To hash the password before save any user, a better aproach is create a pre_save signal or override the save method of User to hash the password (serializer and view will not change)

class User(models.Model):
    ...

    def save(self, **kwargs):
        self.password = make_password(self.password)
        return super(User, self).save(**kwargs)

Make sure the password does not exist or has been changed before call make_password to not encode an already encoded password

Upvotes: 1

Ali
Ali

Reputation: 2591

You can do it in serializer class

class UserSerializer(ModelSerializer):

    class Meta:
        model=User
        fields = ('Username', 'Password', #others)

   def create(self, validated_data):
       user = User()
       user.Username = validated_data['Username']
       user.Password = make_password(validated_data['Password'])
       # other

'make_password' could be any function that you want

Then in view just save the serializer

Upvotes: 3

Related Questions