我在我的 Django 项目中使用基于类的视图来重置密码。我的表单只有一个字段,用户可以在那里写电子邮件地址或用户名。提交成功后,用户可以在同一页面看到成功消息。我的问题是提交后我看到空字段但同时我可以通过单击按钮再次发送数据。提交成功后如何清除表单域?我有点困惑。
视图.py
class PasswordResetRequestView(FormView):
template_name = "registration/password_reset.html"
success_url = '/account/password_reset'
form_class = PasswordResetRequestForm
@staticmethod
def validate_email_address(email):
try:
validate_email(email)
return True
except ValidationError:
return False
def post(self, request, *args, **kwargs):
global data
form = self.form_class(request.POST)
try:
if form.is_valid():
data = form.cleaned_data["email_or_username"]
if self.validate_email_address(data) is True:
associated_users = User.objects.filter(Q(email=data) | Q(username=data))
if associated_users.exists():
for user in associated_users:
c = {
'email': user.email,
'domain': request.META['HTTP_HOST'],
'site_name': 'your site',
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'user': user,
'token': default_token_generator.make_token(user),
'protocol': 'http',
}
subject_template_name = 'registration/password_reset_subject.txt'
email_template_name = 'registration/password_reset_email.html'
subject = loader.render_to_string(subject_template_name, c)
subject = ''.join(subject.splitlines())
email = loader.render_to_string(email_template_name, c)
send_mail(subject, email, DEFAULT_FROM_EMAIL, [user.email], fail_silently=False)
result = self.form_valid(form)
messages.success(request, 'An email has been sent to ' +
data + ". Please check its inbox to continue reseting password.")
return result
result = self.form_invalid(form)
messages.error(request, 'No user is associated with this email address')
return result
else:
associated_users = User.objects.filter(username=data)
if associated_users.exists():
for user in associated_users:
c = {
'email': user.email,
'domain': 'example.info',
'site_name': 'example',
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'user': user,
'token': default_token_generator.make_token(user),
'protocol': 'http',
}
subject_template_name = 'registration/password_reset_subject.txt'
email_template_name = 'registration/password_reset_email.html'
subject = loader.render_to_string(subject_template_name, c)
# Email subject *must not* contain newlines
subject = ''.join(subject.splitlines())
email = loader.render_to_string(email_template_name, c)
send_mail(subject, email, DEFAULT_FROM_EMAIL, [user.email], fail_silently=False)
result = self.form_valid(form)
messages.success(request, 'Email has been sent to ' +
data + "'s email address. Please check its inbox to continue reseting password.")
return result
result = self.form_invalid(form)
messages.error(request, _('This username does not exist in the system.'))
return result
except Exception as e:
print(e)
return self.form_invalid(form)