/registration/api/registration 处的名称错误/名称 'name' 未定义

Name Error at /registration/api/registration/ name 'name' is not defined

实际上,我正在尝试验证序列化程序中给出的字段

Server time:    Thu, 24 Dec 2020 11:29:07 +0000

注意:问题出在验证字段中。 在添加验证字段之前它工作正常。 有人可以帮我解决这个问题吗? 我以为验证很容易,但我遇到了以下问题。

我的serializers.py:

from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from users.models import SuperUser


class RegistrationSerializer(serializers.Serializer):
    email = serializers.EmailField(max_length=200)
    name = serializers.CharField( max_length=200)
    first_name = serializers.CharField( max_length=200)
    last_name = serializers.CharField( max_length=200)
    phone = serializers.IntegerField()
    country = serializers.CharField( max_length=300)
    state = serializers.CharField(  max_length=100)
    city = serializers.CharField(max_length=100)
    zip_code = serializers.IntegerField()
    password = serializers.CharField(style={'input_type':  'password'}, write_only = True)
    confirm_password = serializers.CharField(style={'input_type':  'password'}, write_only = True)



    def validate_email(self, value):
        """
        Check that the email is provided by the user or not.
        """
        if '@gmail.com' not in value.lower():
            raise serializers.ValidationError("your email is not correct")
        return value


    def validate_name(self, value):
        """
        Check that the name is provided by the user or not.
        """
        if name not in value.lower():
            raise serializers.ValidationError("This field may not be empty")
        return value


    def validate_first_name(self, value):
        """
        Check that the first_name is provided by the user or not.
        """
        if first_name not in value.lower():
            raise serializers.ValidationError("This field may not be empty")
        return value


    def validate_last_name(self, value):
        """
        Check that the last_name is provided by the user or not.
        """
        if last_name not in value.lower():
            raise serializers.ValidationError("This field may not be empty")
        return value


    def validate_phone(self, value):
        """
        Check that the phone is provided by the user or not.
        """
        if phone not in value:
            raise serializers.ValidationError("This field may not be empty")
        return value

    def validate_country(self, value):
        """
        Check that the country is provided by the user or not.
        """
        if country not in value.lower():
            raise serializers.ValidationError("This field may not be empty")
        return value


    def validate_state(self, value):
        """
        Check that the state is provided by the user or not.
        """
        if state not in value.lower():
            raise serializers.ValidationError("This field may not be empty")
        return value


    def validate_city(self, value):
        """
        Check that the city is provided by the user or not.
        """
        if city not in value.lower():
            raise serializers.ValidationError("This field may not be empty")
        return value


    def validate_zip_code(self, value):
        """
        Check that the zip_code is provided by the user or not.
        """
        if zip_code not in value:
            raise serializers.ValidationError("This field may not be empty")
        return value


    def save(self):
        account = SuperUser(

            email      = self.validated_data['email'],
            name       = self.validated_data['name'],
            first_name = self.validated_data['first_name'],
            last_name  = self.validated_data['last_name'],
            phone      = self.validated_data['phone'],
            country    = self.validated_data['country'],
            state      = self.validated_data['state'],
            city       = self.validated_data['city'],
            zip_code   = self.validated_data['zip_code'],

            )

        password = self.validated_data['password']
        confirm_password = self.validated_data['confirm_password']

        if password != confirm_password:
            raise ValidationError(_("Both passwords doesn't match"))
        account.set_password(password)
        account.save()
        return account

我的models.py:

from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings

# Create your models here.

class CustomUser(BaseUserManager):

    """
    Custom user model manager where email is the Unique identifier
    for authentication instead of username.
    """
    def _create_user(self, email, password, **extra_fields):
        """
        Create and save a User with the given email and password.
        """
        if not email:
            raise ValueError(_('Email must be provided.'))

        if not password:
            raise ValueError(_('Password must be provided.'))

        email = self.normalize_email(email)  # normalize_email is used to validate the given email.
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password = None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_active', True)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        '''
        It will create a superuser with the given email and password
        '''

        extra_fields.setdefault('is_superuser', True)
        return self._create_user(email, password, **extra_fields)


class SuperUser(AbstractBaseUser, PermissionsMixin):
    """docstring for ClassName"""
    username = None
    email = models.EmailField(_('Email Address'), unique=True)
    name = models.CharField(_('Full Name'), blank=True, max_length=200)
    first_name = models.CharField(_('first Name'), blank=True, max_length=200)
    last_name = models.CharField(_('last Name'), blank=True, max_length=200)
    phone = models.IntegerField(_('phone'), blank=True, default=False)
    country = models.CharField(_('country'), blank=True, max_length=300)
    state = models.CharField(_('state'), blank=True, max_length=100)
    city = models.CharField(_('city'), blank=True,max_length=100, default=False)
    zip_code = models.IntegerField(_('zip-code'), blank=True, default=False)
    is_staff = models.BooleanField(_('is_staff'), default=True)


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name', 'first_name', 'last_name', 'phone','country', 'state', 'city', 'zip_code']

    objects= CustomUser()


    class Meta:
        verbose_name = 'User'
        verbose_name_plural = 'Users'

    def __str__(self):
        return self.email

    
    @receiver(post_save, sender=settings.AUTH_USER_MODEL)
    def token_creation(sender, instance=None, created=False, **kwargs):
        if created:
            Token.objects.create(user=instance)

我收到这个错误:

NameError at /registration/api/registration/
    name 'name' is not defined
    Request Method: POST
    Request URL:    http://127.0.0.1:8000/registration/api/registration/
    Django Version: 3.1.4
    Exception Type: NameError
    Exception Value:    
    name 'name' is not defined
    Exception Location: C:\Users\Royal\Desktop\eign-project\eign_project\users\serializers.py, line 36, in validate_name
    Python Executable:  C:\Users\Royal\Desktop\eign-project\venv\Scripts\python.exe
    Python Version: 3.9.0
    Python Path:    
    ['C:\Users\Royal\Desktop\eign-project\eign_project',
     'C:\Users\Royal\AppData\Local\Programs\Python\Python39\python39.zip',
     'C:\Users\Royal\AppData\Local\Programs\Python\Python39\DLLs',
     'C:\Users\Royal\AppData\Local\Programs\Python\Python39\lib',
     'C:\Users\Royal\AppData\Local\Programs\Python\Python39',
     'C:\Users\Royal\Desktop\eign-project\venv',
     'C:\Users\Royal\Desktop\eign-project\venv\lib\site-packages']

我通过简单地添加一些功能得到了答案,因为验证对我来说效果很好。

def validate_first_name(self, value):
        """
        Check that the first_name is provided by the user or not.
        """
        name = self.get_initial()
        first_name = name.get('first_name')
        if first_name not in value.lower():
            raise serializers.ValidationError("This field may not be empty")
        return value

同样的逻辑可以应用于其他验证字段。