[Answered ]-Django – How to create an object to be used in many views (for a dynamic menu)

2👍

Create a file context_processors.py in your app’s directory. In there, create a function like

def add_sidebar_stuff(request):
    model_urls =  MajorSiteInfoData.objects.only('location')

    return {
        'link_urls': model_urls,
    }

And load it in settings.py

TEMPLATES = [{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    ...
    'OPTIONS': {
        'context_processors': [
            ...
            'my_app.context_processors.add_sidebar_stuff',
            ...

The above adds variables to every template context. That part may or may not be necessary, I don’t know it you are already loading the variable elsewhere.

Then create a partial template partial_menu.html

<ul>
  <li><a href="{% url 'service:showrooms' %}">Showroom</a></li>
{% for link in major_sites %}
  <li><a href="{% url 'service:majorsite' link_urls.id %}">{{ link_urls.location }}</a></li>
{% endfor %}
</ul>

And where-ever you want to show it in your templates, include it.

<div class="sidebar">
    <h3>Service Menu</h3>
    {% include 'service/partial_menu.html' %}
</div>
👤C14L

0👍

In django, you could use the concept of a context processor. Just write a function, which will be called on every request. It must return a dictionary of context you want to add, which in your case will be something like:

def menu_context_processor(request):
    return {
        'link': MajorSiteInfoData.objects.only('location')
    }

After adding this callable to the list of context processors in your TEMPLATES setting, every template rendered will now have link in its context (you might want to use a different name because of this). django documentation on writing your own context processors.

Alternatively, you could write a custom template tag to render this menu. django documentation on writing custom template tags

👤Jieter

Leave a comment