在创建新用户djangorestframework之前检查用户是否存在

时间:2017-11-03 22:29:52

标签: django python-2.7 django-rest-framework django-views django-serializer

到目前为止,我有 - >

串行器:

class UserSerializer(serializers.ModelSerializer):
    """Serializer to map the model instance into json format."""
    class Meta:
        """Map this serializer to a model and their fields."""
        model = User
        fields = ('id','username', 'mobile', 'password', 
                  'first_name','last_name','middle_name', 
                  'profile_pic','short_bio','friends_privacy',
                  'address_1','address_2','city',
                  'state','country','pin','verification_code',
                  'is_active','is_blocked','is_reported',
                  'date_created','date_modified')
        extra_kwargs = {'password': {'write_only': True}}
        read_only_fields = (
            'date_created', 'date_modified',
            'is_staff', 'is_superuser', 'is_active', 
            'date_joined',)
    def create(self, validated_data):
        mobile_ = validated_data['mobile']
        password_ = validated_data['password']
        username_ = validated_data['username']
        motp = self.context['request'].GET['motp']
        eotp = self.context['request'].GET['eotp']
        email_ = self.context['request'].GET['email']
        mflag = api.views.checkOTP_(mobile_,motp)
        eflag = api.views.checkOTP_(email_,eotp)
        if (mflag and eflag):
            user = User(
            username=username_,
            email =email_,
            password = make_password(password_),
            mobile = mobile_,
            )
            user.set_password(validated_data['password'])
            user.save()
            return user

视图:

class UserView2(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    model = User

    def get_permissions(self):
        # allow non-authenticated user to create via POST
        return (AllowAny() if self.request.method == 'POST'
                else IsStaffOrTargetUser()),

我需要检查移动设备和电子邮件的OTP,以及是否已存在具有相同移动设备或电子邮件的用户。 如果用户已存在,则返回错误:already exists!的json响应。 如果用户是新的并且OTP错误再次引发错误。 如果用户是新用户并且OTP正确,请创建一个帐户。

问题在于我尝试添加该功能以检查def create of UserSerializer内的otp验证。但是序列化器应该返回模型实例。但是如果你看到代码,我只能在OTP正确且返回用户实例的情况下创建用户。并且没有else

那么有更好的方法来检查视图本身的OTP吗?

2 个答案:

答案 0 :(得分:1)

我不同意@Anjaneyulu那里.. 序列化程序也处理对象的创建..因此你有serializer.save()

但是为了使用相同的OTP电子邮件/电话为现有用户引发例外,您应该编写自己的def validate_mobile(self, data)def validate_email(self, data)。 DRF序列化程序将首先在类中查找这些方法,并在它们存在时运行它们。因此,检查这些字段的自定义逻辑可能是:

class UserSerializer(serializers.ModelSerializer):   
    def validate_mobile(self, value):
        ModelClass = self.Meta.model
        if ModelClass.objects.filter(mobile=value).exists():
            raise serializers.ValidationError('already exists')
        return value

    def validate_email_(self, value):
        ModelClass = self.Meta.model
        if ModelClass.objects.filter(email_=value).exists():
            raise serializers.ValidationError('already exists')
        return value
    class Meta:
        model = User
        fields = (
            ...,
        )

答案 1 :(得分:0)

这不是实现它的正确方法。序列化程序仅用于验证目的。您不应在序列化程序中实现create方法,而应将其写入ViewSet。创建对象是一种业务逻辑。它应该总是在ViewSet。将验证方法写入序列化程序。我正在编写下面的示例代码

serializers.py

 class UserSerializer(serializers.ModelSerializer):

    def validate_mobile(self, mobile_num):
         is_already_exists = Model.objects.filter(mobile=mobile_num).exists()
         if is_already_exists:
             raise serializers.ValidationError('already exists')
         return mobile_num

    class Meta:
        model = User
        fields = (
           'id','username', 'mobile', 'password',
           'first_name','last_name','middle_name','profile_pic',
           'short_bio','friends_privacy','address_1',
           'address_2','city','state','country',
           'pin','verification_code','is_active',
               'is_blocked','is_reported',
           'date_created','date_modified'
       )
       extra_kwargs = {'password': {'write_only': True}}
       read_only_fields = (
           'date_created', 'date_modified','is_staff',
           'is_superuser', 'is_active', 'date_joined',
       )

Viewsets.py(业务逻辑)

class UserView2(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get_permissions(self):
        # allow non-authenticated user to create via POST
        return (AllowAny() if self.request.method == 'POST'
                else IsStaffOrTargetUser()),
    def create(self, serializer):
          # your logic goes here.