Search code examples
djangodjango-rest-frameworkdjango-rest-framework-simplejwt

does django encode passwords in the Database?


I created a user with a password password123 but in the database the password field look like this pbkdf2_sha256$260000$rJZWVrYXlokRG8fGMS1fek$S7Dm9soflUsy0Q74CJP8sB60tgfRWuRPdqj5XL0DBV0=

  • the problem: is when I create new user via rest framework i got the poassword feidl look like passsword123
  1. so how should i created new user in order to keep the django password encoding functionality
  2. also how to deactivate this password encoding functionality

Solution

  • Django uses encryption middlewares to encrypt passwords (since the database sees passwords as VarChar fields, so Django's model sees them as plain text unless it is told otherwise). If you want the Django User model to use encryption, you must call

    user_obj.set_password(passwd_text) 
    

    With this line of code, you tell Django to run encryption algorithms. For example, in your case, you can first use the serializer's extra_kwargs to exclude passwords from database-readable data, then create the user.

    class CreateUserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ['email', 'username', 'password']
            extra_kwargs = {'password': {'write_only': True}}
    
        def create(self, validated_data):
            password = validated_data.pop("password")
            user = User(**validated_data)
            user.set_password(password)
            user.save()
            return user 
    

    if you want to read more on Django users and passwords read these docs user model doc and encryption types and password management doc