gpt4 book ai didi

View 中的Django Forms自定义错误消息

转载 作者:行者123 更新时间:2023-12-03 15:45:49 24 4
gpt4 key购买 nike

这是我的看法:

if request.method == 'POST':
form = TeacherRegister(request.POST)
#Gets school object from email domain.
email = form['email'].value().split('@')[1]
try:
school = School.objects.get(email_domain = email)
except ObjectDoesNotExist:
#add custom error message here

if form.is_valid():
user, Teacher = form.save()
Teacher.school = school
Teacher.save()
user.groups.add(Group.objects.get(name='Teacher'))
#user.is_active to stop users logging in without confirming their emails

user.is_active = False
user.save()
#Sends confirmation link.
send_confirmation_email(request, user)

args = {'email': user.email,
'link': user.Teacher.school.email_website}

return render(request, 'email/token_sent.html', args)

else:
args = {'form': form,}
return render(request, 'users/teachers.html', args)

这些行是我正在尝试使用的行:
email = form['email'].value().split('@')[1]
try:
school = School.objects.get(email_domain = email)
except ObjectDoesNotExist:
#add custom error message here

这是我用于电子邮件字段的HTML:
<div class="required field" >
{{ form.email.label }}
{{ form.email }}
{{ form.email.help_text }}
<!-- <label>Email</label>
<input placeholder="Email" type="email" name="email" autofocus="" required="" id="id_email"> -->
</div>

如果没有归还学校物品,我怎么能说出类似“找不到学校,请检查您的电子邮件”的字样?

谢谢

最佳答案

您需要在表单侧执行验证。
以以下形式实现 clean_email 方法:

def clean_email(self):
email = self.cleaned_data.get('email')
email = email.split('@')[1]
try:
school = School.objects.get(email_domain = email)
except ObjectDoesNotExist:
raise forms.ValidationError(''School not found, check your email')
return email

现在,在模板中,您可以在 email字段后立即显示此错误:
 {{ form.email.label }}
{{ form.email }}
{{ form.email.errrors }}
{{ form.email.help_text }}

关于 View 中的Django Forms自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48620812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com