1
我正在編寫一個視圖向用戶發送密碼重置電子郵件。我正在檢查用戶輸入的電子郵件是否使用了forms.py中的clean方法進行了註冊,雖然我無法獲得要在django模板中顯示的自定義錯誤消息,但它仍在正常工作。在模板中顯示自定義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 %}