如何在Django中使模型字段成为可选字段?

我做了一个自定义的用户模型,并从使用该模型。我已将电子邮件字段设为可选。起初,我可以将没有电子邮件的数据存储在数据库中。但是每当我第二次尝试不使用电子邮件存储数据时,表单验证器就会给出类似的错误

User signup model with this Email already exists.

如何解决呢?我也尝试从管理员存储,但给出相同的错误。

我的models.py

from django.db import models

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager



class SignUpManager(BaseUserManager):
    def create_user(self, email,age,name, username, password=None):
        #if not email:
            #raise ValueError("insert user")
        if not username:
            raise ValueError("insert username")
        if not name:
            raise ValueError("insert name")
        if not age:
            raise ValueError("insert age")
        user = self.model(
           email=self.normalize_email(email),
           username=username,
           age=age,
           name=name,
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self,email,name,age,username, password):

        user = self.create_user(
            email=self.normalize_email(email),
            username=username,
            password=password,
            age=age,
            name=name,
        )
        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True

        user.save(using=self._db)
        return user


class UserSignupModel(AbstractBaseUser):
    email = models.EmailField(verbose_name="email", max_length=60, unique=True,blank=True,null=True)
    age = models.CharField(max_length=15)
    name = models.CharField(max_length=15)
    username = models.CharField(max_length=15, unique=True)
    date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True)
    last_login = models.DateTimeField(verbose_name="last login", auto_now=True)

    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ['email','name','age']
    objects = SignUpManager()

    def __str__(self):
        return self.name

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True
#migrate --run-syncdb in case no work

我的forms.py

from django import forms

from django.contrib.auth.forms import UserCreationForm
from diabetes.models import UserSignupModel


class UserSignupForm(UserCreationForm):
    email=forms.EmailField(max_length=60,help_text="add a valid email address",required=False)
    name=forms.CharField(max_length=15,help_text="add a valid name")
    age=forms.CharField(max_length=15)

    class Meta:
        model=UserSignupModel
        fields=('email','name',"username",'age',"password1","password2")

我的views.py

from django.shortcuts import render,redirect
from django.contrib.auth import login,authenticate
from diabetes.forms import UserSignupForm


# Create your views here.
def home(request):
    return render(request,'diabetes/home.html')

def signupuser(request):
    context={}
    if request.POST:
        form=UserSignupForm(request.POST)
        if form.is_valid():
            form.save()
            #email=form.cleaned_data.get('email')
            raw_password=form.cleaned_data.get('password1')
            name=form.cleaned_data.get('name')
            age=form.cleaned_data.get('age')
            username=form.cleaned_data.get('username')

            account=authenticate(password=raw_password,name=name,age=age,username=username)
            login(request,account)
            return redirect('home')
        else:
            context["reg_form"]=form

    else:
        form = UserSignupForm()
        context["reg_form"] = form
    return render (request,'diabetes/signupuser.html',context)
评论
  • beos
    beos 回复

    由于您在电子邮件模型字段中设置了unique = True,因此将其设置为blank = True。

    该声明。

    email=self.normalize_email(email)
    

    给予''

    在models.py中,

    为EmailField设置blank = False,null = True 并在SignUpManager中修改此行

    def create_superuser(self,email,name,age,username, password):
    
        user = self.create_user(
            email=self.normalize_email(email) or None,
            ....
    
  • 娇气的小奶包
    娇气的小奶包 回复

    email = models.EmailField(verbose_name =“ email”,max_length = 60,unique = True,blank = True,null = True)

    从代码的这一部分中删除“ unique = True”

  • Me小懒虫
    Me小懒虫 回复

    unique=False
    

    在里面 模型以允许多个空白条目