41π
β
to hash password, call:
make_password(origin_password)
example serializers.py:
from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
class UserSerializer(serializers.HyperlinkedModelSerializer):
password = serializers.CharField(
write_only=True,
required=True,
help_text='Leave empty if no change needed',
style={'input_type': 'password', 'placeholder': 'Password'}
)
class Meta:
model = User
fields = ('url', 'username', 'email', 'password')
def create(self, validated_data):
validated_data['password'] = make_password(validated_data.get('password'))
return super(UserSerializer, self).create(validated_data)
π€HoangYell
8π
Change serializers.py
as below
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ('username', 'email', 'password', 'firstname', 'last name')
def create(self, validated_data):
user = super().create(validated_data)
user.set_password(validated_data['password'])
user.save()
return user
def update(self, instance, validated_data):
user = super().update(instance, validated_data)
try:
user.set_password(validated_data['password'])
user.save()
except KeyError:
pass
return user
π€JPG
- Improving Performance of Django ForeignKey Fields in Admin
- Refresh <div> element generated by a django template
- Why is Django's Meta an old-style class?
3π
There was no special field for password in DRF. In my current project we used to define password field as CharField
with write_only=True
inside serializer class.
π€Shubho Shaha
- Django: Faking a field in the admin interface?
- Django unique together constraint failure?
- How to specify uniqueness for a tuple of field in a Django model
- Create DB Constraint via Django
2π
The @MahdiSorkhmiri answer is working perfectly for me. Here is how my file is looking write now.
class UserSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
validators=[UniqueValidator(UserModel.objects.all())]
)
password = serializers.CharField(
min_length=4,
write_only=True,
required=True,
style={'input_type': 'password'}
)
def create(self, validated_data):
fields = ['username', 'password', 'email']
data = {f: validated_data.get(f) for f in fields}
return UserModel.objects.create_user(**data)
class Meta:
model = UserModel
fields = 'username email last_name first_name password'.split()
π€Mr.Rusev
- Django rest framework model serializers β read nested, write flat
- How to read sql query to pandas dataframe / python / django
- VS Code: Python Interpreter can't find my venv
- Django database synchronization for an offline usage
Source:stackexchange.com