我不了解如何在不重定向错误页面的情况下显示模板错误。 我的任务是检查数据库中是否存在电子邮件,如果不存在,则会在表单中引发错误。
我正在使用Django 2.1和Python 3.7
我所拥有的:django / auth / views.py
class PasswordResetView(PasswordContextMixin, FormView):
email_template_name = 'registration/password_reset_email.html'
extra_email_context = None
form_class = PasswordResetForm
from_email = None
html_email_template_name = None
subject_template_name = 'registration/password_reset_subject.txt'
success_url = reverse_lazy('password_reset_done')
template_name = 'registration/password_reset_for.html'
title = _('Password reset')
token_generator = default_token_generator
@method_decorator(csrf_protect)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def form_valid(self, form):
opts = {
'use_https': self.request.is_secure(),
'token_generator': self.token_generator,
'from_email': self.from_email,
'email_template_name': self.email_template_name,
'subject_template_name': self.subject_template_name,
'request': self.request,
'html_email_template_name': self.html_email_template_name,
'extra_email_context': self.extra_email_context,
}
email = form.cleaned_data['email']
if User.objects.filter(email=email).exists():
form.save(**opts)
return super().form_valid(form)
else:
raise forms.ValidationError('Email is not in database')
return email
它的标准django类,我只是尝试对其进行一些自定义。 它可以工作,但是会在错误页面上重定向用户。
这是一种密码重置
class PasswordResetForm(forms.Form):
email = forms.EmailField(label=_("Email"), max_length=254)
def check_email(self, email):
email = form.cleaned_data['email']
if User.objects.filter(email=email).exists():
return email
else:
return forms.ValidationError('Email does not exist')
我试图在表单中添加检查方法,但是它不起作用(
这是我的模板的代码:
{% if form.errors %}
{{ form.errors.as_text }}
{% endif %}
<form method="post">
{% csrf_token %}
<label for="id_email">Email:</label>
<input type="email" name="email" maxlength="254" required="" id="id_email">
<input type="submit">
</form>