【问题标题】:How to set template variable <title> in Django?如何在 Django 中设置模板变量 <title>?
【发布时间】:2018-12-24 21:28:39
【问题描述】:

我对 Django 非常陌生,正在尝试设置我的第一个个人 CMS 网站。如果很明显,请道歉。我正在从PHP 过渡,所以有时会有点混乱。

我想设置网站的标题“Dashboard|MCA Portal”。站点名称来自 MySQL 数据库 MySQL 查询:

select value from options where `param`='sitename'

知道怎么做吗?

谢谢 基兰

【问题讨论】:

  • x= options.objects.get(param='sitename') x.value 获取此值并发送到模板
  • 在问这样的基本问题之前,您需要先发送Django tutorial。您将定义一个模型,在视图中查询该模型,并将数据发送到模板 - 所有这些都在该教程中进行了描述。

标签: python mysql django django-templates django-views


【解决方案1】:

您可以通过两种方式将标题值传递给 HTML 模板:

1) 覆盖视图 get_context 方法,从数据库中查询值并像我的示例一样传递(python 3.6):

class MyView(TemplateView):
  template_name = '...'
  ....
  def get_context_data(self, **kwargs):
    data = super().get_context_data(**kwargs)
    title = ...  # query from database here
    data['title'] = title
    return data

2) 1 方法的缺点 - 您应该在每个视图中手动实现查询或实现 BaseView 并继承项目中的所有其他视图。你也可以实现上下文处理器,见下面的例子:

# file <project_root>/<app_dir>/context_processor.py
def app_context(request):
  # query from database
  title = ...  # query from database here
  return dict(site_title=title)

......................
# file <settings_dir>/settings.py
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': {
        os.path.join(BASE_DIR, 'templates')
    },
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
            '<app_package>/context_processor.app_context'
        ],
    },
},

]

该方法的优点 - 变量 site_title 可在上下文处理器 django 应用程序的所有模板中访问

在此处查看官方文档编写您自己的上下文处理器 https://docs.djangoproject.com/en/2.0/ref/templates/api/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 2018-03-19
    • 2013-04-16
    • 2011-08-06
    • 2015-07-06
    • 1970-01-01
    • 2012-10-11
    相关资源
    最近更新 更多