Django Rest Framework没有哈希我的密码

时间:2017-09-07 16:43:46

标签: django api django-rest-framework

我正在尝试在我使用Django Rest Framework构建的Blog-API中注册用户。这是我的代码(serializers.py):

from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from rest_framework.serializers import (ModelSerializer,
                                        HyperlinkedIdentityField,
                                        SerializerMethodField)

User = get_user_model()  


class UserCreateSerializer(ModelSerializer):
   class Meta:
       model = User
       fields = [
        'username',
        'email',
        'password',
       ]
    extra_kwargs = {
        'password': {'write_only': True}
    }

    def create(self, validated_data):
        username = validated_data['username']
        email = validated_data['email']
        password = validated_data['password']
        user_obj = User(username=username,
                        email=email)
        user_obj.set_password(password)
        user_obj.save()
        return validated_data

在Django管理员中,用户将按预期显示。但是,密码被称为格式无效。 有人能指出我的解决方案吗?

3 个答案:

答案 0 :(得分:0)

您的create方法应该返回user_obj而不是validate_data。在调用set_password后,你的字符串password似乎覆盖了对象的密码字段,可能是代码中的其他地方?

答案 1 :(得分:0)

我发现了我的错误。 create()方法的愚蠢缩进问题。

from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from rest_framework.serializers import (ModelSerializer,
                                        HyperlinkedIdentityField,
                                        SerializerMethodField)

User = get_user_model()  


class UserCreateSerializer(ModelSerializer):
   class Meta:
       model = User
       fields = [
        'username',
        'email',
        'password',
       ]
    extra_kwargs = {
        'password': {'write_only': True}
    }

def create(self, validated_data):
   username = validated_data['username']
   email = validated_data['email']
   password = validated_data['password']
   user_obj = User(username=username,
                    email=email)
   user_obj.set_password(password)
   user_obj.save()
   return validated_data

答案 2 :(得分:0)

这个问题可以这样解决

class  CreateUserSerializer(serializers.ModelSerializer):
class Meta:
    model = User
    fields = [
        'username',
        'password',
    ]
    extra_kwargs = {
        'password' : {'write_only' : True},
    }

def create(self,validate_data):

    user = User.objects.create_user(username = validate_data['username'] , password = validate_data['password'])

    return user

Views.py(只是调用行)

                temp_data = {
                    'username' : username,
                    'password' : password,
                }
                serializer = CreateUserSerializer(data = temp_data)
                serializer.is_valid(raise_exception = True)                    
                user = serializer.save()

create_user将负责哈希处理。