2016-05-25 69 views
1

我想實現由自定義用戶模型組成的登錄。是否有可能從allauth.account.forms.LoginForm繼承並將自定義字段添加到自定義登錄表單中?Django allauth自定義登錄表單不呈現自定義用戶模型中的所有字段

想法是通過覆蓋 login()方法在登錄時爲用戶分配角色。

我按照allauth configuration並提到在settings.py與下面的代碼

AUTH_USER_MODEL = 'core.User' 
ACCOUNT_SIGNUP_FORM_CLASS = 'core.forms.SignupForm' 
ACCOUNT_FORMS = {'login': 'core.forms.CoreLoginForm'} 

我使用比django.contrib.auth.backends.ModelBackendallauth.account.auth_backends.AuthenticationBackend沒有其他身份驗證後端用什麼形式進行登錄。自定義註冊對我來說沒有任何問題。但是自定義loginform不會呈現用戶模型中的所有字段。 Allauth LoginForm按照此SO Post中的接受答案繼承,並且將選擇字段添加到自定義登錄表單中。

from allauth.account.forms import LoginForm 
class CoreLoginForm(LoginForm): 
    def __init__(self, *args, **kwargs): 
     self.request = kwargs.pop('request', None) 
     super(CoreLoginForm, self).__init__(*args, **kwargs) 
    role = forms.ChoiceField(widget=forms.Select(), choices=User.roles, initial=User.roles[0]) 

在一個./manage.py runserver它說Module "core.forms" does not define a "SignupForm" class。我已經在core.forms中定義了一個SignupForm,如下所示,並且signup will work if CoreLoginForm is inherited from forms.Form instead of LoginForm。所以如果我做

class CoreLoginForm(forms.Form): 
    def __init__(self, *args, **kwargs): 
     self.request = kwargs.pop('request', None) 
     super(CoreLoginForm, self).__init__(*args, **kwargs) 

    role = forms.ChoiceField(widget=forms.Select(), choices=User.roles, initial=User.roles[0]) 

我可以渲染自定義登錄表單到html頁面。但問題是我必須重新定義類中的每種方法,包括authenticate(),perform_login()等。這將最終在複製整個LoginForm並將其粘貼到應用程序的forms.py中。我不想這樣做,因爲我認爲這是違反DRY原則的。有沒有簡單的方法來添加自定義字段到自定義loginform並重寫login()方法?

TIA

回答

3

也許你已經解決了你的問題了,不過

我已經找到了一種簡單的方法我會離開這個解決方案,誰已經花超過10分鐘這個問題和我一樣:)其他人添加一個字段來Allauth登錄表單:

當你做 - 增加的settings.py:

ACCOUNT_FORMS = {'login': 'core.forms.CoreLoginForm'} 

,之後在forms.py你需要一個dd:

from django import forms 
from allauth.account.forms import LoginForm 

class CoreLoginForm(LoginForm): 

    def __init__(self, *args, **kwargs): 
     super(CoreLoginForm, self).__init__(*args, **kwargs) 
     ## here i add the new fields that i need 
     self.fields["new-field"] = forms.CharField(label='Some label', max_length=100) 
+0

有幾種方法可以做到這一點,但我覺得這是最Python/Django的路要走。良好的工作/投票應得到解決和發佈。 –

相關問題