我正在编写一个视图,向用户发送密码重置电子邮件。我正在检查用户输入的电子邮件是否通过使用forms.py中的clean方法进行了注册,这是正常工作,尽管我无法在django模板中显示自定义错误消息。
views.py
def send_forgotten_password_email(request):
heading = 'Reset Password'
if request.method == 'POST':
form = ForgottenPasswordForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
form = ForgottenPasswordForm()
return render(request,'authentication/forms/forgotten_password.html',{
'form':form,
'heading':heading,
})
forms.py
class ForgottenPasswordForm(forms.Form):
email = forms.CharField(
label='Email:',
widget= forms.EmailInput(attrs={'class':'form-control','placeholder':'Enter email'})
)
def clean_email(self):
email = self.cleaned_data['email']
email = get_object_or_none(User,email=email)
if not email:
raise forms.ValidationError("Email not found.")
return email
模板
{% extends "base.html" %}
{% load static %}
{% block title %} Forgotten Password {% endblock title %}
{% block content %}
<div class="row">
<div class="col col-sm-12 col-md-5 col-lg-5">
<div class="card">
<div class="card-body">
<h4 class="card-title">{{heading}}</h4>
<div class="alert alert-danger" role="alert">
{{form.non_field_errors}}
{{form.errors}}
{{forms.errors}}
{{form.email.errors}}
</div>
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label>{{form.email.label}}</label>
{{form.email}}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
{% endblock content %}
答案 0 :(得分:0)
你需要在if语句之前移动空的初始表单:
# Added this
form = ForgottenPasswordForm()
if request.method == 'POST':
form = ForgottenPasswordForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
# Remove this line
# form = ForgottenPasswordForm()