David 天宇 Wong
David 天宇 Wong

Reputation: 4187

Django views : passing a dictionary

I'm starting with Django (coming from CodeIgniter) and everything is very confusing...

I want to get my blog posts ordered by pub_date, and I want to display them in the templates grouped by month+year.

I tried this but obviously it's not working... And my knowledge of Python + Django is so bad that I don't see why not.

def index(request):
    blogs = Blog.objects.order_by('-pub_date')
    blogs_per_date = {}
    for blog in blogs:
        blogs_per_date[blog.pub_date.month + '-' + blog.pub_date.year] = blog
    context = {'blogs': blogs_per_date}
    return render(request, 'layout.html', context);

Here's my try with an object :

def index(request):
    blogs = Blog.objects.order_by('-pub_date')
    blogs_per_date = new object
    for blog in blogs:
        blogs_per_date.blog.(pub_date.month + ' ' + blog.pub_date.year) = blog
    context = {'blogs': blogs_per_date}
    return render(request, 'layout.html', context);

Upvotes: 0

Views: 149

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

You can bypass this by using the regroup tag in your template.

{% regroup blogs by pub_date as blogs_by_date %}

<ul>
{% for blog in blogs_by_date %}
    <li>{{ blog.grouper }}
    <ul>
        {% for item in blog.list %}
          <li>{{ item }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

Your view now is simply:

def index(request):
    objects = Blog.objects.order_by('-pub_date')
    return render(request, 'layout.html', {'blogs': objects})

If you want to do this in your view, you need to create a dictionary, where each key is the date object and the value is a list of blog objects. Something like this will work:

from collections import defaultdict

def index(request):
    by_date = defaultdict(list)
    for obj in Blog.objects.order_by('-pub_date'):
        by_date[obj.pub_date].append(obj)
    return render(request, 'layout.html', {'blogs': by_date})

Now, in your layout.html, you have:

<ul>
{% for key,items in blogs.iteritems %}
    <li>{{ key }}
        <ul>
            {% for item in items %}
            <li>{{ item }}</li>
            {% endfor %}
        </ul>
    </li>
{% endfor %}
</ul>

Upvotes: 3

Related Questions