【问题标题】:Django global variable for base.htmlbase.html 的 Django 全局变量
【发布时间】:2018-05-29 14:15:21
【问题描述】:

我已经实现了一个全局变量,但我真的不知道如何访问它。我发现的例子有点混乱。

models.py

...
# Categorys of Post Model
class Category(models.Model):
    title = models.CharField(max_length=255, verbose_name="Title")


    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"
        ordering = ['title']

    def __str__(self):
        return self.title

#Post Model
class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField(max_length=10000)
    category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)

...

settings.py:

TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"Post.global.category_dropdown",
)

global.py

from .models import Category

def category_dropdown(request):
    categories = Category.objects.all()
    return {'categories': categories}

base.html:

<body>
    <div class="page-header">
        <form method="POST">
            <label>
                <select name="Category">
                    {% for global in category_dropdown %}
                        <option value="{{ categorie.title }}">{{ categorie.title }} {{ categorie.post_set.count }}</option>
                    {% endfor %}
                </select>
            </label>
        </form>
  1. 我不确定它是否以正确的方式实施。
  2. 我不知道如何访问全局变量。在模板中

最后,这应该在每个页面的标题中显示一个下拉菜单,从数据库中获取他的值,正如您在 models.py 中看到的那样

提前致谢

【问题讨论】:

  • 模板标签或上下文处理器。

标签: django variables global


【解决方案1】:

编辑:

我知道你想要什么。我认为您非常接近解决方案,并且您发现的内容与我之前的答案非常相似。主要区别在于,您使用TEMPLATE_CONTEXT_PROCESSORglobal.py 文件中注入上下文。

因此,使用TEMPLATE_CONTEXT_PROCESSORS,您可以在上下文字典中注入上下文变量。例如,如果您有 Form,那么您的上下文如下所示:

{ 
  'form': {
  ...
  }
}

在你的情况下,你总是在里面注入参数 categories 所以你的上下文看起来像:

{ 
  'form': {
  ...
  },
  'categories': [
        {
          'title': 'your title 1'
          'posts': [...]
        },
        {
          'title': 'your title 2'
          'posts': [...]
        },
        ....
   ]
}

所以你可以做的是在你的 HTML 代码中访问这个上下文变量。

<body>
  <div class="page-header">
    <form method="POST">
      <label>
        <select name="Category">
          {% for category in categories %}
            <option value="{{ category.title }}">{{ category.title }} {{ category.post_set.count }}</option>
          {% endfor %}
        </select>
      </label>
    </form>

因为字典中变量的名称是“category”,(并且包含您的类别数组)您应该在 for 循环中访问此变量。当您遍历类别时,您会创建名为 category(或任何其他名称)的临时变量,并使用此变量来访问标题和帖子数。

上一个:

我不确定你要什么。

但您可能需要在context_data 中始终包含类别列表。

这意味着您可以准备一些函数来获取所有类别并从中创建上下文,例如:

def prepare_category_context(context_data):
    """
    Function that create context data for all Views classes. 
    """
    context_data['categories'] = model.Category.objects.all()
    return  context_data


class myView(generic.EnyViewClass):
    """
    Example of the View Class. This could be generic.TemplateView, CreateView,...
    The trick is to add context data inside class.
    """

    def get_context_data(self, **kwargs):
        """
        Here we defined context data that will be used in templates.
        We call our function here. But we need to call super first, if we have some form data or any thing else already in context...
        """
        context = super().get_context_data(**kwargs)
        context = self.prepare_category_context(context)
        return context

【讨论】:

猜你喜欢
  • 2014-01-30
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 2011-01-14
  • 1970-01-01
  • 2016-05-16
  • 1970-01-01
相关资源
最近更新 更多