【问题标题】:Django custom PasswordResetFormDjango 自定义 PasswordResetForm
【发布时间】:2014-06-28 18:18:07
【问题描述】:

我正在尝试使用 PasswordResetForm 内置函数。

因为我想要自定义表单字段,所以我编写了自己的表单:

class FpasswordForm(PasswordResetForm):
    email = forms.CharField(max_length=30, widget=forms.TextInput(attrs={'autofocus': 'autofocus'}))
    class Meta:
        model = User
        fields = ("email")
    def clean_email(self):
        email = self.cleaned_data['email']
        if function_checkemaildomain(email) == False:
            raise forms.ValidationError("Untrusted email domain")
        elif function_checkemailstructure(email)==False:
            raise forms.ValidationError("This is not an email adress.")

        return email

这是我在views.py中的观点

@cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True)
def fpassword(request):
    form = FpasswordForm(request.POST or None)
    if form.is_valid():
        email = form.cleaned_data["email"]
        if function_checkemail(email):
            form.save(from_email='blabla@blabla.com', email_template_name='registration/password_reset_email.html')
            print "EMAIL SENT"
        else:
            print "UNKNOWN EMAIL ADRESS"

我的电子邮件模板是:

{% autoescape off %}
You're receiving this e-mail because you requested a password reset for your user account at {{ site_name }}.

Please go to the following page and choose a new password:
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url "django.contrib.auth.views.password_reset_confirm" uidb36=uid token=token %}
{% endblock %}

Your username, in case you've forgotten: {{ user.username }}

Thanks for using our site!

The {{ site_name }} team.

{% endautoescape %}

问题是我有一个'NoneType' object has no attribute 'get_host' 错误...回溯日志告诉我在current_site = RequestSite(request) 中,请求是None。 也许我在views.py 中的save() 中还有其他内容要添加?

当我在表单和内置视图中使用以下没有自定义字段的方法时,一切正常:http://garmoncheg.blogspot.com.au/2012/07/django-resetting-passwords-with.html

【问题讨论】:

    标签: django forms python-2.7


    【解决方案1】:

    所以您收到该错误是因为它试图在设置为None 的实例上调用方法。这是您应该使用的正确视图:

    @cache_control(max_age=0, no_cache=True, no_store=True, must_revalidate=True)
    def fpassword(request):
        form = FpasswordForm(request.POST or None)
        if form.is_valid():
            email = form.cleaned_data["email"]
            if function_checkemail(email):
                form.save(from_email='blabla@blabla.com', email_template_name='registration/password_reset_email.html', request=request)
                print "EMAIL SENT"
            else:
                print "UNKNOWN EMAIL ADRESS"
    

    另一个选项是启用Django Sites Framework。然后您就不必传递请求,因为get_current_site 将返回站点当前实例。这是该逻辑的link

    【讨论】:

    • 您可以将 'domain_override' kwarg 添加到 save 方法中,它也应该绕过该错误。如form.save(domain_override="yourdomain.com")
    猜你喜欢
    • 2013-10-26
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2010-12-24
    • 2021-09-01
    • 2020-12-15
    • 2011-11-28
    相关资源
    最近更新 更多