如何在Django allauth中更改“已存在的帐户”消息?

时间:2014-12-17 06:58:37

标签: django django-allauth

当尝试使用社交帐户登录时,如果已经有该电子邮件的帐户,则会显示以下消息:

An account already exists with this e-mail address. Please sign in to that account first, then connect your Google account.

现在我想改变那条消息。起初我试图覆盖ACCOUNT_SIGNUP_FORM_CLASS = 'mymodule.forms.MySignupForm'并给它自己的raise_duplicate_email_error方法,但该方法永远不会被调用。

表格如下:

class SignupForm(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()
    boolflag = forms.BooleanField()

    def raise_duplicate_email_error(self):
        # here I tried to override the method, but it is not called
        raise forms.ValidationError(
            _("An account already exists with this e-mail address."
              " Please sign in to that account."))

    def signup(self, request, user):
        # do stuff to the user and save it 

所以问题是:如何更改该消息?

2 个答案:

答案 0 :(得分:4)

如果要调用raise_duplicate_email_error方法,则必须从实际调用self.raise_duplicate_email_error()的表单类继承!但是,您只是继承自forms.Form

让我们看一下https://github.com/pennersr/django-allauth/blob/master/allauth/account/forms.py forms.py的代码。我们可以看到raise_duplicate_email_errorBaseSignupForm的方法(并且从clean_email方法调用)。

因此,您需要继承allauth.account.forms.BaseSignupFormallauth.account.forms.SignupForm(也继承自BaseSignupForm并为其添加更多字段)。

OP评论后更新BaseSignupForm派生自_base_signup_form_class()函数,该函数本身导入SIGNUP_FORM_CLASS setting中定义的表单类:嗯你是对的。问题是raise_duplicate_email_error的{​​{1}}和clean_email方法不会通过super调用其祖先的同名方法(因此永远不会调用您的BaseSignupForm)。

让我们看看视图的作用:如果您已将行raise_duplicate_email_error添加到urls.py(这是django-allauth的常用操作),您将看到行{{1}在文件https://github.com/pennersr/django-allauth/blob/13edcfef0d7e8f0de0003d6bcce7ef58119a5945/allauth/account/urls.py中,然后在文件中 https://github.com/pennersr/django-allauth/blob/13edcfef0d7e8f0de0003d6bcce7ef58119a5945/allauth/account/views.py您会看到注册的定义为url(r'^accounts/', include('allauth.urls')),。因此,让我们覆盖url(r"^signup/$", views.signup, name="account_signup"),以使用我们自己的表单,然后使用signup = SignupView.as_view()的类视图!

以下是如何操作:

一个。创建继承SignupView并覆盖表单类

的自定义视图
class CustomFormSignupView(allauth.accounts.views.SignupView):
    form_class = CustomSignupForm

湾创建一个继承自account_sigunp的自定义表单,并覆盖电子邮件验证消息

class CustomSignupForm(allauth.accounts.forms.SignupForm ):
    def raise_duplicate_email_error(self):
        # here I tried to override the method, but it is not called
        raise forms.ValidationError(
            _("An account already exists with this e-mail address."
              " Please sign in to that account."))

℃。在您自己的urls.py中添加以下 SignupView后覆盖SignupForm网址

    url(r'^accounts/', include('allauth.urls')),
    url(r"^accounts/signup/$", CustomFormSignupView.as_view(), name="account_signup"),``

答案 1 :(得分:0)

创建覆盖raise_duplicate_email_error方法的CustomSignupForm(allauth.accounts.forms.SignupForm)后,您可以使用版本0.18将以下内容添加到设置文件中:

SOCIALACCOUNT_FORMS = {
    'signup': 'path.to.your.custom.social.signup.form.CustomSignupForm'
}

现在应该调用新的raise_duplicate_email_error方法。

希望这会对你有所帮助。