base.html的Django全局变量 [英] Django global variable for base.html

查看:59
本文介绍了base.html的Django全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了全局变量,但是我真的不知道如何访问它.我发现的示例有些混乱.

i've implemented a global variable but i dont really know how to access it. The examples i have found are a bit confusing.

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中看到的那样.

In the end this should display a dropdown menu in the header of every page wich gets his value from the database as you can see in models.py

预先感谢

推荐答案

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

I see what you want. I think you are very close to a solution, and what you found is very similar to my previous answer. The main difference is, that you inject context in a global.py file with TEMPLATE_CONTEXT_PROCESSOR.

因此,使用 TEMPLATE_CONTEXT_PROCESSORS ,您可以将上下文变量注入上下文字典中.例如,如果您具有Form,则您的上下文看起来像:

So with TEMPLATE_CONTEXT_PROCESSORS you inject the context variables in your context dictionary. For example, if you have Form then your context looks like:

{ 
  'form': {
  ...
  }
}

在您的情况下,您总是在内部插入参数 categories ,因此您的上下文看起来像:

in your case you always inject the parameter categories inside so your context looks like:

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

因此,您可以做的是在HTML代码中访问此上下文变量.

So what you could do is access this context variable inside your HTML code.

<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 (或任何其他名称)的临时变量,并使用此变量来访问标题和帖子数.

Because the name of the variable in dictionary is 'category', (and contains array of your categories) you should access this variable in your for loop. When you iterate trough categories you create temporary variable named category (or any other name) and use this variable to access title and number of posts.

我不确定您要什么.

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

But what you probably need is to have category list always inside your context_data.

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

This mean that you can prepare some function that fetch all Category and create context from it like :

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

这篇关于base.html的Django全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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