Klaaavs
Klaaavs

Reputation: 13

How to make a GET request in an extended Django template

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

Answers (3)

Sid
Sid

Reputation: 2189

Try a custom template tag. Steps involved:

  1. Create a directory templatetags at the same level as your view, with an __init__.py
  2. Create a file in templatetags with any name e.g. make_get_request.py
  3. In that file, enter something like this:
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
  1. Restart server.
  2. In the template, write {% load make_get_requests %} i.e. the file name.
  3. Use the function in the template, like:
{% get_request %}

Upvotes: 0

Lewis
Lewis

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

Jure C.
Jure C.

Reputation: 3080

There are few ways:

  1. You could implement a custom template tag
  2. You could write your own custom context processor and inject it into every rendered templateenter link description here

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

Related Questions