如何在django中使用API​​返回多个值

时间:2018-05-08 06:45:20

标签: json django api

我是django的新手。

这是我从互联网上调用的api json值:

{'message': '',
 'result': [{'name': 'ABC',   <------
             'Type': 'True',  <-----
             'Fee': 0.0005},
             {'name': 'DEF', <-------
             'Type': 'False',  <------
             'Fee': 0.004},
}

我想使用HTML将名称和类型放到网页上。

ABC True
DEF False

我需要修改models.py吗?请举个例子。谢谢 我知道的唯一想法是在HTML中使用for循环,但我不知道它是否有效?

2 个答案:

答案 0 :(得分:1)

只需在模板中使用forloop。

{% for r in result %}
{{ r.name }} {{ r.Type }}
{% endfor %}

使用view

更新了答案

您的result来自context

基本上,django view将数据呈现给您自己的模板。 context_processors为您执行此操作,并在settings.pyTEMPLATES - OPTIONS - context_processors)中定义。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            str(ROOT_DIR.path('templates')),
        ],
        # 'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                # you can add your own processors
                'your_app.path.to.custom_processors',
            ],
            'loaders': [
                'django.template.loaders.filesystem.Loader',
                'django.template.loaders.app_directories.Loader',
            ],
        },
    },
]

以下是有关contextofficial django docs

的详细信息

这就是您可以在模板中使用requestuser和其他上下文数据的原因。

如果要在所有模板中使用上下文,可以添加自己的context_processors。但在很多时候,您只想在特定模板中使用上下文。 (就像你的情况一样)。

然后,您可以在views

中将数据添加到上下文中

如果您使用的是基于类的视图(我建议使用CBV),您可以按get_context_data()添加。像这样。

class ProductView(ListView):
    model = Product
    template_name = 'best.html'
    context_object_name = 'products'

    def get_context_data(self, **kwargs):
        context = super(ProductView, self).get_context_data(**kwargs)
        context['test'] = 'test context data'
        return context

您可以在现有context中添加自己的上下文数据。

如果您正在使用FBV,则可以使用您的上下文渲染模板。有很多种呈现方式(renderrender_to_response等等。您可以检查django文档。我猜您应该使用render因为render_to_response已弃用在django 2.0

from django.shortcuts import render

def my_view(request):
    # View code here...
    context = {'test': 'test coooontext data' }
    return render(request, 'myapp/index.html', context)

通过在视图中传递您自己的上下文数据,您可以在模板中使用它。

因此,如果您只想传递'name'和'type',您可以传递您想要使用的数据,而不是全部。在视图模板中工作更有效。我希望它有所帮助。

答案 1 :(得分:0)

在view.py

您可以返回

等数据
url = 'xxx'
response = requests.get(url)
# if your response is like : {'message': '', 'result': [{'name': 'ABC',  'Type': 'True', 'Fee': 0.0005}, {'name': 'DEF','Type': 'False', 'Fee': 0.004}] }
# then

list_result = response['result']

render(request, 'template.html', {"list_result": list_result})

然后,您可以在HTML页面上发送list_result并使用

导入render
from django.shortcuts import render

要在HTML页面上显示响应数据:

{% for data in list_result %}
  {{ data.name }} {{ data.Type }}
{% endfor %}