Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python HttpResponse中的Django额外上下文项_Python_Django - Fatal编程技术网

Python HttpResponse中的Django额外上下文项

Python HttpResponse中的Django额外上下文项,python,django,Python,Django,我的观点定义如下: class HomeView(TemplateView): template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['items'] = Item.objects.all() return context

我的观点定义如下:

class HomeView(TemplateView):
    template_name = "home.html"

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        context['items'] = Item.objects.all()
        return context

    def get(self, request, *args, **kwargs):

        #Getting data from an api call here
        response = api.get_some_items()
        list_with_items = []
        for i, item in enumerate(response):
            list_with_items.append(item.name)

        template = loader.get_template('home.html')
        context = self.get_context_data(**kwargs)
        context['extra_items'] = list_with_items

        return HttpResponse(template.render(context, request))
在模板中,我循环遍历列表,如下所示,但它似乎没有呈现该上下文中的任何内容,我知道这一点,因为我在其中放置了
{%empty%}
标记

{% for item in items %}
    {{ item }}
{% empty %}
    <p>No items</p>
{% endfor %}
{items%]中的项的%
{{item}}
{%empty%}
没有项目

{%endfor%}
这里出了什么问题


编辑:当我将跟踪放在HttpResponse之前时,
context['extra_items']
返回了列表中的所有项目,但没有将其呈现到模板中

我认为您弄乱了基于类的视图。为什么要为此使用
TemplateView

您可以尝试以下方法:

from django.views.generic.list import ListView


class HomeView(ListView):
    model = Item
    context_object_name = 'items'
    template_name = "home.html"

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        response = api.get_some_items()
        list_with_items = []
        for i, item in enumerate(response):
            list_with_items.append(item.name)
        context['extra_items'] = list_with_items
        return context

我认为你搞乱了基于类的视图。为什么要为此使用
TemplateView

您可以尝试以下方法:

from django.views.generic.list import ListView


class HomeView(ListView):
    model = Item
    context_object_name = 'items'
    template_name = "home.html"

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        response = api.get_some_items()
        list_with_items = []
        for i, item in enumerate(response):
            list_with_items.append(item.name)
        context['extra_items'] = list_with_items
        return context