Django Rest Framework创建用户自定义序列化允许相同的电子邮件

时间:2016-03-13 06:50:46

标签: python django authentication django-rest-framework

我正在尝试使用其余框架创建用户,但我可以使用相同的电子邮件创建多个用户,如何验证所收到的电子邮件?

这是我的序列化代码:

from django.contrib.auth.models import User
from django.contrib.auth import get_user_model

class UserSerializer(serializers.ModelSerializer):
    invoices = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    password = serializers.CharField(write_only=True)

    def create(self, validated_data):
        user = get_user_model().objects.create(
            email=validated_data['email'],
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

    class Meta:
        model = User
        write_only_fields = 'password'
        read_only_fields = 'id'
        fields = ('id',
                  'username',
                  'email',
                  'password',
                  'invoices',
                  )

提前致谢!

3 个答案:

答案 0 :(得分:4)

好的,进一步阅读REST FRAMEWORK documentation,有“唯一字段”验证器,通过添加它,它可以很好地工作。

email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all())])

所以它看起来像这样

class UserSerializer(serializers.ModelSerializer):
invoices = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
password = serializers.CharField(write_only=True)
email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all())])

def create(self, validated_data):
    user = get_user_model().objects.create(
        email=validated_data['email'],
        username=validated_data['username']
    )
    user.set_password(validated_data['password'])
    user.save()
    return user

class Meta:
    model = User
    write_only_fields = 'password'
    read_only_fields = 'id'
    fields = ('id',
              'username',
              'email',
              'password',
              'invoices',
              )

感谢您的支持!

答案 1 :(得分:2)

您应该能够在模型电子邮件字段中设置unique = true约束,而不是在序列化程序中自己编写。

https://docs.djangoproject.com/en/1.9/ref/models/fields/#unique

答案 2 :(得分:-1)

复制并粘贴此代码。它的工作..

from django.contrib.auth.models import User
from django.contrib.auth import get_user_model

class UserSerializer(serializers.ModelSerializer):
    invoices = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        write_only_fields = 'password'
        read_only_fields = 'id'
        fields = ('id',
                  'username',
                  'email',
                  'password',
                  'invoices',
                  )

        def create(self, validated_data):
        user = User.objects.filter(email=validated_data['email'])
        if user:
            raise serializers.ValidationError("The email '" +
                                              validated_data['email'] +
                                              "' already exists")
        else:
            return User.objects.create_user(**validated_data)

代码中唯一的变化是

def create(self, validated_data):
    user = User.objects.filter(email=validated_data['email'])
    if user:
        raise serializers.ValidationError("The email '" +
                                          validated_data['email'] +
                                          "' already exists")
    else:
        return User.objects.create_user(**validated_data)

在此功能中,我使用电子邮件获取用户详细信息。如果用户退出并显示错误“电子邮件xyz@xyz.com已退出。 或者,如果用户不存在,则创建用户。