【问题标题】:API data in Django listviewDjango 列表视图中的 API 数据
【发布时间】:2017-07-11 15:53:32
【问题描述】:

无法弄清楚如何将 API 中的数据添加到 Django 中的列表视图中。我正在使用 django-restframework,并为我的部分数据提供了内部 API。最终,我想将 Freight 模型中的所有信息显示到列表视图中。我知道我必须创建一个上下文,但我不确定如何处理 API 数据。到目前为止,这是我的代码:

@method_decorator(login_required, name='dispatch')
class ManifestEngineView(ListView):
    model = Freight
    template_name = 'pages/engine.html'

    def get_context_data(self, **kwargs):
        freight_list = requests.get('http://localhost:8000/api/freight/').json()
        for freight in freight_list:
            print(freight['pu_customer'])

我可以将客户名称打印到控制台,但我不知道如何将它放在我可以传递给我的模板并使用的上下文中。模板应该有一个包含模型中所有必要数据的框。

更新的模板代码:

<div id="origin" class="fbox">
            {% for f in freight.pu_customer %}
                <span class="freight draggable">
                {{ f }}
                </span>
            {% endfor %}
    </div>

【问题讨论】:

    标签: django django-views api-design


    【解决方案1】:
     def get_context_data(self, **kwargs):
            context = super(ManifestEngineView, self).get_context_data(**kwargs)
            freight_list = requests.get('http://localhost:8000/api/freight/').json()
            for freight in freight_list:
                context['something'] = freight 
            return context
    

    试试这个并在模板中

    {% for f in something %}
    {{ f }}
    {% endfor %}
    

    【讨论】:

      【解决方案2】:
          def get_context_data(self, **kwargs):
              context = super(ManifestEngineView, self).get_context_data(**kwargs)
              context['frieght']={}
              freight_list = requests.get('http://localhost:8000/api/freight/').json()
              context['frieght']['pu_customer'] = frieght_list
              return context
      

      【讨论】:

        【解决方案3】:

        API 旨在用于模板、Ajax、Jquery。 在您的情况下,您只需使用 ListView;

        在views.py中

        class ManifestEngineView(ListView):
            model = Freight
            template_name = 'pages/engine.html'
            context_object_name = 'list_freights' 
        

        在您的模板中

         {% for item in list_freights %} //what you named your context
            <tr>
                <td>{{ item.pu_customer }}</td>
        </tr>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-30
          • 2015-05-09
          • 2020-07-15
          • 2018-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-14
          相关资源
          最近更新 更多