简体   繁体   中英

Make custom variable in Django Context permanent

I'm creating a website which has "categories" as a model in 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. How should I do to set categories as a context variable for any future View?

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. http://catherinetenajeros.blogspot.com/2013/03/custom-template-context-processors.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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