【问题标题】:How to return multiple values using API in django如何在 django 中使用 API 返回多个值
【发布时间】:2023-03-17 13:45:01
【问题描述】:

我是 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循环,但我不知道它是否有效?

【问题讨论】:

    标签: json django api


    【解决方案1】:

    只在模板中使用forloop。

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

    view 更新了答案

    您的result 来自context

    基本上,django view 将数据渲染到您自己的模板。 context_processors 为你做这件事,它在 settings.py (TEMPLATES - 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',
                ],
            },
        },
    ]
    

    这里有更多关于context (official 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_responsedjango 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)
    

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

    因此,如果您只想传递“名称”和“类型”,则可以只传递您想要使用的数据,而不是全部。在视图中工作比在模板中更有效。我希望它有所帮助。

    【讨论】:

    • 谢谢,但我很难知道“结果”变量来自哪里?我需要先在views.py中设置def变量吗?
    • 这取决于您的view。我会更新view的答案
    • 感谢您的更新!这样我对 settings.py () 中的 TEMPLATES 了解更多
    【解决方案2】:

    在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 %}
    

    【讨论】:

    • 它说“响应”对象不可下标。 url = 'xxx' get = requests.get(url) response = get['result']
    • get 的结果是什么?
    • 谢谢!有用!我没有把 {"list_result": list_result} 放在渲染的末尾!
    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 2017-08-06
    相关资源
    最近更新 更多