簡體   English   中英

/registration/api/registration/ 名稱錯誤未定義名稱“名稱”

[英]Name Error at /registration/api/registration/ name 'name' is not defined

實際上,我正在嘗試驗證序列化程序中給出的字段

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

注意:問題在驗證字段中。 在添加驗證字段之前它工作正常。 有人可以幫我解決這個問題嗎? 我認為驗證很容易,但我遇到了以下問題。

我的序列化程序.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

我的模型.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

並且相同的邏輯可以應用於其他驗證字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM