用于base.html的Django全局变量

时间:2018-05-29 14:15:22

标签: django variables global

我实现了一个全局变量,但我真的不知道如何访问它。我发现的例子有点令人困惑。

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. 我不知道如何访问全局变量。在模板
  3. 最后,这应该在每个页面的标题中显示一个下拉菜单,它从数据库中获取其值,如models.py中所示

    提前致谢

1 个答案:

答案 0 :(得分:0)

编辑:

我明白你想要什么。我认为你非常接近解决方案,你发现的与我以前的答案非常相似。主要区别在于,您使用global.pyTEMPLATE_CONTEXT_PROCESSOR文件中注入了上下文。

因此,使用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>

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

PREVIOUS:

我不确定你要求的是什么。

但你可能需要的是让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