【问题标题】:Custom User Model with multiple Unique id - Django RestFramework具有多个唯一 ID 的自定义用户模型 - Django Rest 框架
【发布时间】:2021-07-11 04:37:46
【问题描述】:

您好 StackOverFlow 朋友们, 我已经为我的项目创建了一个自定义用户模型,并希望使用 Restframework 注册用户。

我希望自定义用户模型有 2 个唯一字段,为此我遵循“Official doc”作为 unique_together 属性。它似乎只将 1 个字段(即我的案例的电子邮件)作为唯一字段。

到目前为止,我的相关代码如下所示: PS:如果需要更多信息,请告诉我。

models.py

class MasterUser(AbstractBaseUser):
    email = models.EmailField(verbose_name='email address',max_length=255,unique=True,)
    firstname = models.CharField(max_length=100,blank=True)
    contact = models.CharField(max_length=100, blank=True)

    objects = MyUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['firstname']
    class Meta:
        unique_together = (('email', 'contact'),)

serializer.py

class RegisterUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(style={'input_type': 'password'}, write_only= True)

    class Meta:
        model = MasterUser
        fields = ('firstname', 'password', 'password2', 'email','contact')
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def save(self):
        account = MasterUser(
            email = self.validated_data['email'],
            firstname = self.validated_data['firstname'],
            contact = self.validated_data['contact'],
        )

        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'password': 'Password doesnt matches'})
        account.set_password(password)
        account.save()
        return account

views.py

@api_view(['POST'])
def registration_view(request):
    if request.method == "POST":
        serializer = RegisterUserSerializer(data= request.data)
        data = {}
        if serializer.is_valid():
            account = serializer.save()
            data['response'] = "Successfully registered new user!"
        else:
            data = serializer.errors
        return Response(data)

我在哪里缺少实现的东西?

【问题讨论】:

    标签: python-3.x django django-rest-framework


    【解决方案1】:

    unique_together 表示您定义的字段集对于所有用户应该是唯一的。如果您还希望联系人在存储在 db 中时成为唯一字段,则应像这样传递唯一参数:

    class MasterUser(AbstractBaseUser):
        ...
        contact = models.CharField(max_length=100, blank=True, unique=True)
        ...
    
    

    【讨论】:

    • 我真傻!我第一次尝试类似电子邮件,但没有成功,并立即寻找其他方法。现在它起作用了!谢谢杰奇!
    猜你喜欢
    • 2020-08-09
    • 2018-08-19
    • 2017-02-02
    • 2016-08-06
    • 2022-11-15
    • 1970-01-01
    • 2017-03-27
    • 2016-05-30
    • 1970-01-01
    相关资源
    最近更新 更多