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
- setup()
- dispatch()
- http_method_not_allowed()
- 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.
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'})
- [Django]-Is it possible to install a django package without pip?
- [Django]-Django-Debug-Toolbar not showing(disallowed MIME type)
- [Django]-Django: best way to define a form to insert long texts?
- [Django]-Serializing Model in Python/Django Template
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 ),
]
- [Django]-Django openid authentication with google
- [Django]-Django admin ignores has_delete_permission