dnsko dnsko - 13 days ago 5
Python Question

Django extra context item in HttpResponse

I have my view defined as follow:

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))


In the template I loop through the list as follow, but it does not seem to render anything from that context, which I know because I put the
{% empty %}
tag in there.

{% for item in items %}
{{ item }}
{% empty %}
<p>No items</p>
{% endfor %}


What does go wrong here?

EDIT: When I put a trace right before the HttpResponse,
context['extra_items']
returned all the items in the list, but does not render it to the template

Answer

I think you are messing up with Class based views. Why would you use TemplateView for this?

You may try something like this instead:

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