[Django]-Django – passing variable from function view into html template

2πŸ‘

βœ…

i am going to answer your question in terms of django, you will have to figure out how to get request from external api from their docs.

According to django docs: A TemplateView’s Method Flowchart is

  1. setup()
  2. dispatch()
  3. http_method_not_allowed()
  4. get_context_data()

now you are using

def index(request, template_name="index.html"):
    headers = {'Authorization': 'my_private_api'}
    args={}
    request = Request('https://avwx.rest/api/metar/KJFK', headers=headers)
    response_body = urlopen(request).read()
    args['metar'] = response_body
    return TemplateResponse(request,template_name,args)

which is not going to work beacuse this def index(... is not executed at all. so you have nothing in your context metar

so changing your code to:

class DashboardView(TemplateView):
    template_name = "index.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        #headers = {'Authorization': 'my_private_api'}
        #request = Request('https://avwx.rest/api/metar/KJFK',headers=headers)
        #response_body = urlopen(request).read()

        context['metar'] = 'some information'
        return context

will give you metar as 'some information' in your template.

πŸ‘€Ansuman

1πŸ‘

You could use the render function to simplify this.

e.g.

from django.shortcuts import render

def index(request, template_name="index.html"):
    return render(request, template_name, {'metar': 'Hello world'})
πŸ‘€Richard

0πŸ‘

After looking at your code, I got to know that you have two views as DashboardView which is a template view and another index which is function based view (and you have configured it improperly). In Urls you have configured DashboardView as your view handler and your actual api code lies in index that’s why it was not working. Following solution is based on function based view, this might help.

views.py

from django.shortcuts import render
from urllib.request import Request, urlopen

def index(request):
    headers = {'Authorization': 'my_private_api'}
    request = Request('https://avwx.rest/api/metar/KJFK', headers=headers)
    response_body = urlopen(request).read()
    context = {
    'metar':response_body
    }
    return render(request,'index.html',context=context)

template.html

{%block content %}
<div>
   <h1>Metary</h1>
   <p>{{ metar }}</p>
</div>
{%endblock content%}

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index ),
]
πŸ‘€k33da_the_bug

Leave a comment