我的函数在django项目中不起作用

2021-08-02 17:45:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正尝试使用以下文本字段(email、country和phone number)以json或api视图格式返回数据,但是我还有两个验证函数来验证email和phone number字段中的值,这两个字段需要get()方法并使用它将文本作为参数传递。我不确定这两个验证功能是否正常工作,因为当我输入一封无效的电子邮件时,它仍然被接受为有效数据。请告诉我我做错了什么,应该对我当前的代码做什么更改。你知道吗

/* serializers.py */
import re
import phonenumbers
from rest_framework import serializers
from .models import validation
from phonenumbers import carrier
from validate_email import validate_email


class validationSerializer(serializers.ModelSerializer):

    class Meta:
        model = validation
        fields = '__all__'

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if not validate_email(email, check_mx=True, verify=True):
            raise serializers.ValidationError("Invalid email")
        return email

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get("phone_number")
        clean_number = re.sub("[^0-9&^+]", "", phone_number)
        alpha_2 = self.cleaned_data.get("country")
        z = phonenumbers.parse(clean_number, "%s" % (alpha_2))
        if len(clean_number) > 15 or len(clean_number) < 3:
            raise serializers.ValidationError(
                "Number cannot be more than 15 or less than 3")
        if not phonenumbers.is_valid_number(z):
            raise serializers.ValidationError(
                "Number not correct format or non-existent")
        if carrier.name_for_number(z, "en") == '':
            raise serializers.ValidationError("Please enter a mobile number")
        return phonenumbers.format_number(
            z, phonenumbers.PhoneNumberFormat.E164)

/* models.py */
from django.db import models


class validation(models.Model):
    email = models.EmailField()
    country = models.CharField(max_length=2)
    phone_number = models.CharField(max_length=100)

    def __str__(self):
        return self.email
3条回答
网友
1楼 ·

Clean用于模型,validate用于序列化程序。所以必须使用validate而不是clean。根据这个例子格式化你的代码。还有,而不是自清理的\u数据使用自我验证的数据. 你知道吗

from rest_framework import serializers

class EventSerializer(serializers.Serializer):
    description = serializers.CharField(max_length=100)
    start = serializers.DateTimeField()
    finish = serializers.DateTimeField()

    def validate(self, data):
        """
        Check that start is before finish.
        """
        if data['start'] > data['finish']:
            raise serializers.ValidationError("finish must occur after start")
        return data

    def validate_description(self, value):
        """
        Check that event is related to django.
        """
        if 'django' not in value.lower():
            raise serializers.ValidationError("It is not a django event")
        return data

在您的情况下,您可以像这样重写电子邮件验证。你知道吗

def validate_email(self):
    email = self.validated_data.get("email")
    if not self.validate_email(email, check_mx=True, verify=True):
        raise serializers.ValidationError("Invalid email")
    return email
网友
2楼 ·

if语句没有从函数返回,它应该给出validationerror,但在这之后它仍然返回电话号码。你知道吗

可以在if语句中返回函数,也可以使用如下结构:

if not phonenumbers.is_valid_number(z):
   raise serializers.ValidationError(
      "Number not correct format or non-existent")
elif carrier.name_for_number(z, "en") == '':
   raise serializers.ValidationError("Please enter a mobile number")
else:
   return phonenumbers.format_number(
         z, phonenumbers.PhoneNumberFormat.E164)
网友
3楼 ·

也许您正在寻找Validators,您可以创建一个验证函数并在kwargsvalidators=下的字段中指定它

链接中的一部分:

def validate_even(value):
    if value % 2 != 0:
        raise ValidationError(
            _('%(value)s is not an even number'),
            params={'value': value},
        )

     -
even_field = models.IntegerField(validators=[validate_even])

相关问题