使用 Django 在我的模板库中显示表单 [英] Show a Form in my template base using Django

查看:25
本文介绍了使用 Django 在我的模板库中显示表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的基本模板中,我想包含一个搜索表单.

In my base template, I want to include a search form.

我已经创建了它,但我想知道是否有比将 form 传递给扩展基础的所有模板更好的选择?

I already created it, but I'm wondering if there is a better option than passing the form to all my templates that extend the base?

推荐答案

是的,这就是模板上下文处理器的用途.它们允许您将变量传递给所有模板,而无需指定.

Yea, this is what template context processors are useful for. They allow you to pass a variable to all your templates without having to specify.

settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',

    ...

    'some_app.context_processors.search_form',
)

context_processors.py(您可以将它放在您的一个应用程序中,或者如果您愿意,可以放在主目录中)

context_processors.py (you place this in one of your apps, or in the main directory if you prefer)

from my_forms import MySearchForm

def search_form(request):
return {
     'search_form' : MySearchForm()
}

现在您可以在所有模板中使用 {{ search_form }}

Now you can use the {{ search_form }} in all of you templates

这篇关于使用 Django 在我的模板库中显示表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆