2011-01-10 55 views
12

所以,現在我正在做基本的登錄。在urls.py,我去Django的contrib請登錄:如何擴展Django「登錄」表單?

(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html'}), 

那它拍攝到這裏:

@csrf_protect 
@never_cache 
def login(request, template_name='registration/login.html', 
      redirect_field_name=REDIRECT_FIELD_NAME, 
      authentication_form=AuthenticationForm): 

這視圖使用AuthenticationForm形式模型:

class AuthenticationForm(forms.Form): 
    """ 
    Base class for authenticating users. Extend this to get a form that accepts 
    username/password logins. 
    """ 
    username = forms.CharField(label=_("Username"), max_length=30) 
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput) 

所以.. 我的目標是改變用戶名形式!通過添加它:widget = forms.TextInput(attrs={'placeholder': 'username'})。而已。這就是我想添加到用戶名輸入框中的全部內容。但是,我不想改變實際的django forms.py文件,因爲這是django contrib的一部分,我感覺不好改變那個文件。

我該怎麼辦?我應該創建一個擴展AuthenticationForm的表單嗎?如果是這樣,我該如何導入?我如何通過我的urls.py將其作爲參數傳入?我不知道該怎麼辦。

回答

21

您需要繼承AuthenticationForm類,然後你需要改變你的urls.py

class MyAuthenticationForm(AuthenticationForm): 
    # add your form widget here 
    widget = ..... 

然後導入這個類到您的urls.py文件和更新的號召,

(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html', 'authentication_form':MyAuthenticationForm}), 

我太累了查找文檔站點上的鏈接,看看你需要使用什麼類型的領域,但這應該做的竅門,讓你開始,而無需修改你de的django forms.py有限應該改變感覺不好!

1

由於milkypostman表示,您需要創建一個auth.forms.AuthenticationForm的子類。

然後,您可以使用django-crispy-forms將佔位符放入所需的字段中。它是如此簡單:

(應用程序/ forms.py)

class LoginWithPlaceholder(AuthenticationForm): 

    def __init__(self, *args, **kwargs): 
     super(LoginWithPlaceholder, self).__init__(*args, **kwargs) 
     self.helper = FormHelper() 
     self.helper.form_show_labels = False 
     self.helper.layout = Layout(Div(Field('username', placeholder='username'), css_class="form-group"), 
            Div(Field('password', placeholder='password'), css_class="form-group"), 
            Div(Submit('submit', 'Log in'))) 

最後,不要忘記使用香脆標籤在你的模板:

<div class="col-sm-6 col-sm-offset-3">   
{% crispy form %}    
</div> 
+0

感謝指向脆皮! – rikb 2017-03-14 17:56:52