不能让我的脑袋绕着一件事:
在Django文档中,您说使用SuccessMessageMixin时可以做类似的事情:
success_message =“%(name)s已成功创建”
其中(名称)是视图使用的表单的字段。
我正在尝试在PasswordResetView的成功消息中添加用户名。默认情况下,PasswordResetView具有称为“ PasswordResetForm”的形式,并且该形式只有我已经使用的1个字段“ email”。 示例--- success_message =“带有说明的电子邮件已发送到您的电子邮件-%(email)s”
# original Django code
class PasswordResetView(PasswordContextMixin, FormView):
email_template_name = 'registration/password_reset_email.html’
extra_email_context = None
form_class = PasswordResetForm # this form
# original Django code
class PasswordResetForm(forms.Form):
email = forms.EmailField(label=_("Email"), max_length=254) # this field
我正在尝试以某种方式进行操作:
success_message = "Email with the instructions has been sent to your email - %(email)s, %(username)s"
但是问题是,如果此表单只有1个字段“电子邮件”,该在哪里获取用户名?
有趣的是,PasswordResetForm有一个名为get_users()的方法,在这里我们可以从以下位置获取用户名:
def get_users(self, email):
"""Given an email, return matching user(s) who should receive a reset.
This allows subclasses to more easily customize the default policies
that prevent inactive users and users with unusable passwords from
resetting their password.
"""
active_users = UserModel._default_manager.filter(**{
'%s__iexact' % UserModel.get_email_field_name(): email,
'is_active': True,
})
return (u for u in active_users if u.has_usable_password())
这似乎是一项有趣的任务,但我无法理解如何将它们结合在一起,以便能够将用户名添加到成功消息中。
尝试过以下操作:
class PRForm(PasswordResetForm):
custom_user = forms.CharField(max_length=30, widget=forms.HiddenInput(), show_hidden_initial=True, initial=???) # some connections to def get_users(self, email) maybe???
根据默认表单创建新表单,并在其中添加隐藏字段custom_user a,但我不知道缩写的类型。然后,我将可以潜在地在success_message中使用此字段。 您对这种方法有什么看法或完全愚蠢?
无论如何,如果有人有任何想法,我将很高兴听到。 我可以没有这项任务,没有问题,但是解决它对我来说似乎很有趣。
自己弄清楚了:
class PRForm(PasswordResetForm):
def clean_email(self):
email = self.cleaned_data['email']
if not ExtraUser.objects.filter(email__iexact=email, is_active=True, is_activated=True).exists():
msg = "There is no user registered with the specified E-Mail address."
self.add_error('email', msg)
else:
current_user = ExtraUser.objects.get(email__iexact=email, is_active=True, is_activated=True)
if current_user:
self.cleaned_data["username"] = current_user
return email
现在可以这样编写成功消息:
success_message = "Dear %(username)s , email with the instructions has been sent to your email - %(email)s"
答案 0 :(得分:0)
亲自发现:
class PRForm(PasswordResetForm):
def clean_email(self):
email = self.cleaned_data['email']
if not ExtraUser.objects.filter(email__iexact=email, is_active=True, is_activated=True).exists():
msg = "There is no user registered with the specified E-Mail address."
self.add_error('email', msg)
else:
current_user = ExtraUser.objects.get(email__iexact=email, is_active=True, is_activated=True)
if current_user:
self.cleaned_data["username"] = current_user
return email
1)定义当前用户
2)将其传递给cleaned_data,因为Django从表单的清除数据中获取此%()s类型标签