django - 模型表单中的 Django 电子邮件验证错误(注册)
问题描述
如果使用该电子邮件的用户已经存在,我正在尝试验证注册表单的电子邮件,它应该显示一个错误,例如电子邮件已经存在,但我无法使用以下代码实现这一点
表格.py
from django.forms import ModelForm
from django import forms
from . models import signup
class signupForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = signup
fields = ['username', 'email' , 'password','confirm_password']
def clean(self):
cleaned_data = super(signupForm, self).clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
raise forms.ValidationError(
"password and confirm_password does not match"
)
email = self.cleaned_data.get('email')
try:
match = signup.objects.get(email=email)
print(match)
except signup.DoesNotExist:
# Unable to find a user, this is fine
return email
# A user was found with this as a username, raise an error.
raise forms.ValidationError('This email address is already in use.')
class loginForm(ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = signup
fields = ['email','password']
它在 /signup 'str' 对象处显示 AttributeError 没有属性 'get' 这个错误
解决方案
如果没有匹配项,您将从 clean 方法返回电子邮件字符串。但是主要clean
方法应该返回整个cleaned_data dict,而不是单个字段。
但无论如何,验证逻辑的那部分应该放在特定clean_email
方法中,该方法确实需要返回电子邮件字符串。所以你会有:
def clean_email(self):
email = self.cleaned_data.get('email')
try:
match = signup.objects.get(email=email)
print(match)
except signup.DoesNotExist:
# Unable to find a user, this is fine
return email
# A user was found with this as a username, raise an error.
raise forms.ValidationError('This email address is already in use.')
def clean(self):
cleaned_data = super(signupForm, self).clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
raise forms.ValidationError(
"password and confirm_password does not match"
)
return cleaned_data
(请注意,与此问题无关,但您的登录表单不应是 ModelForm;这将导致其他验证问题。)
推荐阅读
- c++ - 针对第 n 个素数执行时间优化的 c++ 函数
- frida - 有没有办法在 Frida 中访问“this”?
- python - 管理生成器的 Pythonic 方式
- javascript - 如何在使用 Vuetify 2.x 的表中自定义默认行中使用 v-html?
- html - selenium.common.exceptions.ElementNotInteractableException:消息:元素不可交互
- android - OkHttp POST 请求设置 withCredentials 为 True?
- elasticsearch - 如何在对 Elasticsearch 的 API 请求中指定租户?
- mysql - 为什么 MySQL 为明确定义的列显示未知列?
- javascript - 三元函数执行比 JS 中的 if 语句更好还是更差
- python - 如何将张量与向量相乘?