Answer the question
In order to leave comments, you need to log in
How to send variable to Django template?
Good day! Help plz solve the problem!!!
There is a main.html template, there is a sidebar (sidebar.html) with a list of cars, which is shown depending on the open car, and if this is the main page, then display the last three, for example, that is, I need to pass some kind of variable there. How can I send a variable to sidebar.html? Yes, it is possible, of course, to prescribe and send data in each view, but is it possible to automate this somehow? That is, I registered it in some global variable, or set the logic for the sidebar.
And is there any way to write logic for the sidebar? That is, that he had his own class. I understand that making requests inside the template is a bad practice.
Answer the question
In order to leave comments, you need to log in
Why in the header??? On the site it is written in black and white to insert before the closing tag</body>
In the header, leave only tags <link>
and <style>
between the tag <head></head>
The rest in the footer before closing </body>
And remove </body>
from the header. Something tells me he doesn't belong there.
I see two options:
1. Work through context_processors . Create your own processor class and add it to the settings. Then it will work on any page. Inside this processor, process urls and so on.
context_processors.py
from django.core.context_processors import request
def sidebar(request):
return {'context_auto': ...}
TEMPLATES = [
{ ...,
'OPTIONS': {
'context_processors': [
"context_processors.sidebar",
],
},
},
]
{% include "sidebar.html" %}
display your sidebar through it. That is, you create a function in which you write the logic and loading sidebar.html and on the page you already include the function, and not html @register.inclusion_tag('sidebar.html', takes_context=True)
def sidebar(context):
return ...
{% sidebar %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question