API Django 列表视图中的数据

API data in Django listview

无法弄清楚如何将数据从 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>
 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 %}
    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

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>