【问题标题】:Django - passing variable from function view into html templateDjango - 将变量从函数视图传递到 html 模板
【发布时间】:2020-08-09 23:28:16
【问题描述】:

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

Views.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%}

urls.py

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

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

【问题讨论】:

    标签: python django django-rest-framework django-views django-templates


    【解决方案1】:

    我将用 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 作为'some information' 提供给您。

    【讨论】:

      【解决方案2】:

      你可以使用渲染函数来简化这个。

      例如

      from django.shortcuts import render
      
      def index(request, template_name="index.html"):
          return render(request, template_name, {'metar': 'Hello world'})
      

      【讨论】:

      • 我做到了,但是当我在 index.html 中传递 {{metar}} 时,我什么也没得到。
      • 您的“def index”视图不在您的urlpatterns 中?所以它使用DashboardView 代替。尝试在那里添加它而不是DashboardView
      【解决方案3】:

      查看您的代码后,我知道您有 两个视图DashboardView 是一个模板视图,另一个 index 是基于函数的视图(并且您已经配置了它不当)。在 Urls 中,您已将 DashboardView 配置为您的视图处理程序,而您的实际 api 代码位于 index 中,这就是它不起作用的原因。以下解决方案基于基于功能的视图,这可能会有所帮助。

      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)
      

      模板.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 ),
      ]
      

      【讨论】:

      • 我没有测试它,因为它包含 api 调用,但如果你有任何错误,请告诉我。
      猜你喜欢
      • 2015-05-23
      • 2018-07-17
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 2021-07-17
      相关资源
      最近更新 更多