I am following this tutorial but facing these problems I can't fix:
My code:
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('password', 'first_name', 'last_name', 'email')
write_only_fields = ('password',)
def restore_object(self, attrs, instance=None):
# call set_password on user object. Without this
# the password will be stored in plain text.
user = super(UserSerializer, self).restore_object(attrs, instance)
user.set_password(attrs['password']) #somehow not hashing
return user
Permissions are used to grant or deny access for different classes of users to different parts of the API. The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the IsAuthenticated class in REST framework.
I tried the accepted answer in DRF 3.0.2 and it didn't work. The password was not being hashed.
Instead, override the create method in your model serializer
def create(self, validated_data):
user = User(email=validated_data['email'], username=validated_data['username'])
user.set_password(validated_data['password'])
user.save()
return user
This hashes the password when you create a user using the rest framework, not post_save
Another approach for DRF 3.X:
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
def create(self, validated_data):
if validated_data.get('password'):
validated_data['password'] = make_password(
validated_data['password']
)
user = get_user_model().objects.create(**validated_data)
return user
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With