Django新手如此對不起如果這很瑣事將forms.form導入模板
我有一個由許多其他模板擴展的「base.html」模板。在這個「base.html」模板中,我有一個從「forms.Form」派生類生成的表單,名爲「SearchForm」
。 的問題是:我可以導入「SearchForm」進入了「base.html文件」模板,而不是傳遞「Searchform」作爲上下文是從「base.html文件」
Django新手如此對不起如果這很瑣事將forms.form導入模板
我有一個由許多其他模板擴展的「base.html」模板。在這個「base.html」模板中,我有一個從「forms.Form」派生類生成的表單,名爲「SearchForm」
。 的問題是:我可以導入「SearchForm」進入了「base.html文件」模板,而不是傳遞「Searchform」作爲上下文是從「base.html文件」
Use Django's template context processor得出每一個觀點。
這裏有一個簡單的例子:
def search_form_context_processor(request):
return {'form': SearchForm() }
然後更新您的settings.py
與
TEMPLATE_CONTEXT_PROCESSORS = (
....
my_module.search_form_context_processor,
....
)
https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
在此之後,{{ form }}
將可在任何模板,您呈現使用render_to_response
用RequestContext
傳入。
其他選項(除了@ Derek的)是有一個自定義模板標籤,A)寫入表單html,或B)將表單添加到頁面上下文。
Like Issac Kelly寫道你可以創建一個模板標籤,它將添加到你的上下文中。文檔是here。
要添加形式對上下文,你可以寫
class FormNode(template.Node):
def render(self, context):
context['form'] = MyForm()
return ''
def add_form_to_context(parser, token):
return FormNode()