简体   繁体   English

使Django Context中的自定义变量永久

[英]Make custom variable in Django Context permanent

I'm creating a website which has "categories" as a model in Django. 我正在创建一个网站,该网站在Django中具有“类别”作为模型。 To generate the sidebar, I iterate the categories and create a link for each one, which allows my to make it dinamic. 为了生成侧边栏,我对类别进行了迭代,并为每个类别创建了一个链接,这使我可以使其成为动态的。

The issue is that with the current approach, I have to put Categories.objects.all() as a variable in the context on every view, and I'm sure this is not the correct approach. 问题在于,使用当前方法,我必须在每个视图的上下文中将Categories.objects.all()作为变量,并且我确定这不是正确的方法。 How should I do to set categories as a context variable for any future View? 如何为将来的任何View设置categories作为上下文变量?

An Approach would be writing a context processor , you just have to define a function that returns a context like this: 一个方法将编写一个上下文处理器 ,您只需要定义一个返回上下文的函数,如下所示:

def get_my_cool_context(request):
    return {}

and there you return all the variables you would like to use in all your views and then in all yours views you get your context like this 然后返回所有要在所有视图中使用的变量,然后在所有视图中得到如下所示的上下文

context = get_my_cool_context(request)

make a context processor, like: 制作一个上下文处理器,例如:

def categories(request):   #written in some file named processor.py
    return {'categories': Categories.objects.all()}

then add this context processor: 然后添加此上下文处理器:

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "myapp.processor.categories",         #you have added this line to settings
)

now you can use foo to any template as context variable. 现在您可以对任何模板使用foo作为上下文变量。 http://catherinetenajeros.blogspot.com/2013/03/custom-template-context-processors.html http://catherinetenajeros.blogspot.com/2013/03/custom-template-context-processors.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM