即使所有输入字段都已填写,“此字段是必需的”也会继续显示
Posted
技术标签:
【中文标题】即使所有输入字段都已填写,“此字段是必需的”也会继续显示【英文标题】:"This field is required" keeps showing even all the input field is filled 【发布时间】:2021-02-24 09:25:54 【问题描述】:请帮忙。注册页面一直显示此字段为必填错误。我是初学者。谢谢你
models.py
从 django.db 导入模型
从 django.contrib.auth.models 导入 AbstractBaseUser、BaseUserManager
类 UserManager(BaseUserManager):
def create_user(self, email, username, full_name, password=None):
if not email:
raise ValueError("Users must have an email adress")
if not username:
raise ValueError("Users must have a username")
if not password:
raise ValueError("Users must have a password")
if not full_name:
raise ValueError("Users must have a name")
user = self.model(
email=self.normalize_email(email), # return lowercase
username=username,
full_name=full_name,
)
user.set_password(password) # users set password and change password
user.full_name = full_name
user.save(using=self._db)# using the default database in settings.py
return user
def create_superuser(self, email, username, full_name, password=None):
user = self.create_user(
email=self.normalize_email(email), # return lowercase
username=username,
full_name=full_name,
password=password,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db) # using the default database in settings.py
return user
类帐户(AbstractBaseUser):
email = models.EmailField(
verbose_name="email",
max_length=60,
unique=True,
)
username = models.CharField(max_length=30, unique=True)
full_name = models.CharField(max_length=30, blank=True, null=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)
profile_image = models.ImageField(max_length=255, null=True, blank=True, default=default_profile)
hide_email = models.BooleanField(default=True)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username", "full_name"]
objects = UserManager() # tie account to my custom user manager
def __str__(self):
return self.username
# "Does the user have a specific permission?"
def has_perm(self, perm, obj=None):
return True
# "Does the user have permissions to view the app `app_label`?"
def has_module_perms(self, app_label):
return True
views.py
从 django.shortcuts 导入渲染,重定向
从 django.contrib.auth 导入登录、注销、身份验证
从 account.forms 导入 RegistrationForm、AccountAuthenticationForm
def register_view(请求):
user = request.user
if user.is_authenticated:
return redirect('home')
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email').lower()
raw_password = form.cleaned_data.get('password1')
user = authenticate(email=email, password=raw_password)
login(request, user)
return redirect('home')
else:
form = RegistrationForm()
return render(request, 'account/register.html', 'registration_form': form)
定义登录视图(请求):
context =
user = request.user
if user.is_authenticated:
return redirect("home")
if request.POST:
form = AccountAuthenticationForm(request.POST)
if form.is_valid():
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
return redirect("home")
else:
form = AccountAuthenticationForm()
context['login_form'] = form
return render(request, "account/login.html", context)
def logout_view(请求): 注销(请求) 返回重定向(“家”)
forms.py
从 django 导入表单
从 django.contrib.auth 导入 get_user_model
从 .models 导入帐户
从 django.contrib.auth 导入验证
用户 = get_user_model()
类RegistrationForm(forms.ModelForm):
full_name = forms.CharField()
email = forms.EmailField(max_length=60, help_text='Required. Add a valid email address.')
password1 = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(widget=forms.PasswordInput, label='Confirm password')
class Meta:
model = Account
fields = (
'email',
'username',
'full_name',
'password1',
'password2',
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.email = self.cleaned_data.get('email')
user.username = self.cleaned_data.get('username')
user.full_name = self.cleaned_data.get('full_name')
if commit:
user.save()
return user
def clean_email(self):
email = self.cleaned_data.get('email')
qs = User.objects.filter(email=email)
if qs.exists():
raise forms.ValidationError(f"Email email is already taken")
return email
def clean_username(self):
username = self.cleaned_data.get('username')
qs = User.objects.filter(username=username)
if qs.exists():
raise forms.ValidationError(f"Username username is already taken")
return username
def clean(self):
data = self.cleaned_data
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password2 != password1:
raise forms.ValidationError("Passwords must match")
return data
类 AccountAuthenticationForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
class Meta:
model = Account
fields = ('email', 'password')
def clean(self):
if self.is_valid():
email = self.cleaned_data.get('email')
password = self.cleaned_data.get('password')
if not authenticate(email=email, password=password):
raise forms.ValidationError("Incorrect username or password")
【问题讨论】:
你能复制你看到的(整个)确切的错误吗? @MilesDavis 我认为错误只是出现在 register.html 页面中,上面写着“此字段是必需的” 【参考方案1】:问题的原因可能是username
字段和email
字段被使用了一个代替另一个。
上面提到的代码中的一个例子:
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username", "full_name"]
可以通过验证和修复这些错误来解决问题,其中使用电子邮件字段代替用户名字段,反之亦然。
【讨论】:
【参考方案2】:您的字段 html id 和 name 很可能有错误,因此表单验证将其注册为空值
【讨论】:
以上是关于即使所有输入字段都已填写,“此字段是必需的”也会继续显示的主要内容,如果未能解决你的问题,请参考以下文章