2013-10-20 43 views
0

我想知道如果以下是可能的,需要一個例子。在Django中如何創建呈現登錄表單的模板標記?

我想創建一個呈現登錄表單的模板標籤。請這樣做和指導。

背後的原因是我有一個登錄表單,需要在我網站的每個頁面上。我已經決定這會更好,因爲我可以包括一個標籤。我想使用我的forms.py中的表單,而不是對它進行硬編碼。

from django import template 
from accounts.forms import AuthenticationForm 

register = template.Library() 


def authentication_form(): 
    render this form == AuthenticationForm() ????? 

回答

4

你需要創建一個inclusion tag是呈現模板的標籤。

首先定義例如模板名爲_tag_auth_form.html文件:

<form method="post" action="{{ action }}"> 
    {% csrf_token %} 
    {{ form }} 
    <input type="submit" /> 
</form> 

那麼你的模板標籤只是呈現用適當的環境變量上面的模板:

from django import template 
from accounts.forms import AuthenticationForm 

register = template.Library() 

@register.inclusion_tag('_tag_auth_form.html') 
def authentication_form(): 
    return {'form': AuthenticationForm(), 'action': '/some/url'} 
相關問題