Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping problem with dictionary in Django templates

I'm not sure why this template is not rendering anything to the page. Is there anything obvious I am missing here?

View:

@user_passes_test(is_staff)
def details_activity_log(request, project_id, template='projects/details_activity_log.html'):

    project = get_object_or_404(Project.objects.select_related(), pk=project_id)
    action_log = project.projectactionlog_set.all()

    log_group = defaultdict(list)

    for log in action_log:
        log_group[log.action_time.strftime('%y%m%d')].append(log)


    #import pdb; pdb.set_trace()

    return render_to_response(template, {
        'log_group'  : log_group,
        'project'    : project,
        'action_log' : action_log,
        'tab_5'      : 'active',
    }, context_instance=RequestContext(request))

log_group contains a dict of model objects like so:

defaultdict(<type 'list'>, {'110614': [<ProjectActionLog: ProjectActionLog object>, ...]}) 

Template:

   {% for key, log in log_group %}
      {% for action in log %}
        {{ action }}
        {{ action.action_time }}                    
        {{ action.user.first_name }}
        {{ action.message }}
        {{ action.object_name }}
      {% endfor %}
    {% endfor %}

Edit If only I had looked in the docs I would have seen the answer. https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for

However it's a tricky situation since the templates don't throw any runtime errors when the loop can't unpack the iterator items.

like image 807
Keyo Avatar asked Jun 21 '11 03:06

Keyo


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

How do I sort a dictionary in Django?

You can't sort a dictionary, you can sort representation of a dictionary. Dictionary has a random ordered members. I hope this helps. If i'm doing this: sorted_dict = sorted(data['scoruri'].

Can I use while loop in Django?

The key point is that you can't do this kind of thing in the Django template language.


2 Answers

Change

{% for key, log in log_group %}

to

{% for key, log in log_group.items %}
like image 103
John Avatar answered Oct 06 '22 01:10

John


Update your for loop to:

{% for log in log_group.itervalues %}

Or, if you actually need key (your example template doesn't show you using it):

{% for key, log in log_group.iteritems %}
like image 22
TM. Avatar answered Oct 06 '22 01:10

TM.