Reputation: 13
I have a simple navigation bar base.html
, that contains links to other pages. Currently, I am extending the base.html
template on every other page I have. I want to call a GET request from a weather API in order to display simple information like the city name and current temperature and have it displayed on the navigation bar. Since the base.html
template isn't linked with a view itself, I am unsure how to go about this. I have already managed to succesfully get information from the API and display the information in a test page.
base.html:
<body>
<div class="container-fluid bg-light">
<div class="d-flex flex-wrap align-items-center justify-content-center justify-content-lg-start">
<i class="far fa-newspaper fa-5x"></i>
<a href="{% url 'news_list:homepage' %}" class="nav-link link-dark display-4">Ziņu portāls</a>
<ul class="nav align-items-center ms-auto me-auto">
<li><a href="{% url 'news_list:all_posts' %}" class="nav-link link-dark pt-4"><h2>Visi raksti</h2></a></li>
<li><a href="{% url 'news_list:new_post' %}" class="nav-link link-dark pt-4"><h2>Pievienot rakstu</h2></a></li>
<li><h2>Information from API</h2></a></li>
</ul>
</div>
<hr/>
</div>
{% block content %}{% endblock content %}
</body>
Upvotes: 1
Views: 562
Reputation: 2189
Try a custom template tag. Steps involved:
templatetags
at the same level as your view, with an __init__.py
templatetags
with any name e.g. make_get_request.py
from django import template
register = template.Library()
@register.filter(name = 'get_request')
def get_request():
#make your request here
#return a list, dict etc. with the info you need
{% load make_get_requests %}
i.e. the file name.{% get_request %}
Upvotes: 0
Reputation: 2798
Create a template context processor as seen in This answer
You will then want to render this into your base.html
in order to apply to all templates in your application.
Upvotes: 0
Reputation: 3080
There are few ways:
Each approach has its own tradeoffs. Since you're trying to display dynamic data, watch out for your own caching or hitting too many external services that would slow down rendering (so that you don't make it blocking).
Upvotes: 1