电子邮件字段需要django.contrib.auth

时间:2015-05-21 18:15:45

标签: django django-rest-framework django-rest-auth

如果提供了所有用户名,密码和电子邮件字段,我想在django-rest-auth中注册用户。 (我也希望实现令牌身份验证以从服务器获取JSON响应。)

django.contrib.auth.User中的默认电子邮件字段是可选的。但我想根据需要设置电子邮件,以便在数据库中注册,以便在没有电子邮件的情况下发出POST请求时,用户会收到HTTP错误响应。

在项目中,我通过以下代码注册新用户。

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', User.USERNAME_FIELD, "password", 'full_name',
                  'is_active', 'links', )
        write_only_fields = ('password',)
        read_only_fields = ('id',)

    def create(self, validated_data):
        print("Validated Data",validated_data)
        if 'email' in validated_data:
            user = get_user_model().objects.create(
                username=validated_data['username']
            )
            user.set_email(validated_data['email'])
            user.set_password(validated_data['password'])
            user.save()
            email = EmailMessage('Hello', 'World',
                                 to=[validated_data['email']])
            email.send()
            user.is_active=False
            return user
        else:
            return None

但是,上面给出了:

  

create()没有返回对象实例

如何将电子邮件字段设置为必填字段?

1 个答案:

答案 0 :(得分:0)

  

如果提供了所有用户名,密码和电子邮件字段,我想在django-rest-auth中注册用户。

在Django REST框架中对序列化程序要求字段的正确方法是set required=True when initializing the fieldusing the extra_kwargs parameter将其设置在自动生成的字段上。

  

在django.contrib.auth.User中的默认电子邮件字段中是可选的。但我想根据需要设置电子邮件,以便在数据库中注册,以便在没有电子邮件的情况下发出POST请求时,用户会收到HTTP错误响应。

这意味着默认情况下不需要自动生成的字段,但您仍然可以使用required=True覆盖它。

  

但是,上面给出了:

     
    

create()没有返回对象实例

  

这是因为您没有从User方法返回create个实例,就像它在锡上所说的那样。具体而言,如果未包含None字段,则返回emailNone不是User个实例,DRF警告您,您做错了。

相关问题