gpt4 book ai didi

python - Django - 将变量从函数 View 传递到 html 模板

转载 作者:行者123 更新时间:2023-12-05 03:53:53 24 4
gpt4 key购买 nike

下午好,我有一个问题,我不知道该怎么做。我正在使用第三方 api 获取数据,我将其存储到 metar 变量中并将其作为参数传递。但是它不起作用。任何帮助将不胜感激。谢谢。

View .py

from urllib.request import Request, urlopen
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.template.response import TemplateResponse
# Create your views here.
class DashboardView(TemplateView):
template_name = "index.html"

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)

index.html

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

网址.py

from django.urls import path
from . import views
from dashboard.views import DashboardView

urlpatterns = [
path('', DashboardView.as_view()),
]

最佳答案

我将根据 Django 来回答你的问题,你必须弄清楚如何从他们的文档中获取来自外部 API 的请求。

根据 django 文档:A TemplateView's Method Flowchart is

  1. 设置()
  2. 调度()
  3. http_method_not_allowed()
  4. get_context_data()

现在你正在使用

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)

这是行不通的,因为这个 def index(... 根本没有执行。所以你的上下文中没有任何内容 metar

因此将您的代码更改为:

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

会给你 metar 作为模板中的“一些信息”

关于python - Django - 将变量从函数 View 传递到 html 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61441429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com