Bassline Soup
Bassline Soup

Reputation: 23

Django template iterate over context list

I can't find a clear answer on this. I have a view that shows multiple models. In my template, I have written out everything to manually display what I want but it doesn't really stick to DRY so I'd like to iterate over the context. What I can't find is what the context object is referenced as in my template? I have written pseudo code in the template snippet below of what I want to achieve.

Edited to simplify: The code in the template works in Django shell but not in the template

template.html

{% for object in object_list %}
    {% for key, value in object.items %}
        {% if key == 'string' %}
             <h2>{{ value }}</h2>
        {% endif %}
    {% endfor %}
{% endfor %}

views.py

class ConfigurationDetailView(LoginRequiredMixin, TemplateView):
    ''' Returns a view of all the models in a configuration '''
    template_name = 'configurator/configuration_detail.html'

    def get_context_data(self, **kwargs):
        ''' Uses a list of dictionaries containing plural strings and models to
        filter by the configuration ID to only show items in the config. '''
        context = super(ConfigurationDetailView, self).get_context_data(**kwargs)
        context_dict = [
            {'string':'integrations', 'model': IntegrationInstance},
            {'string':'control_groups', 'model':  ControlGroup},
            {'string':'endpoints', 'model': Endpoint},
            {'string':'scenes', 'model': Scene},
            {'string':'actions', 'model': Action},
            {'string':'smart_scenes', 'model': SmartScene},
            {'string':'buttons', 'model': Button},
            {'string':'button_actions', 'model': ButtonAction},
        ]
        for item in context_dict:
            for key, value in item.items():
                if key == 'string':
                    string = value
                else:
                    model = value
            context[string] = model.objects.filter(config_id__exact=self.kwargs['config_id'])
        return context

Upvotes: 0

Views: 1663

Answers (1)

mohammed wazeem
mohammed wazeem

Reputation: 1328

By default, the context is rendered by a variable called object_list. So you can iterate like

{% for i in object_list %}
  // do something 
{% endfor %}

You can override the variable name by defining context_object_name attribute on a generic view, which specifies the context variable to use

class MyView(ListView):
    ...
    ...
    context_object_name = "context"

Upvotes: 2

Related Questions