Django视图:传递字典 [英] Django views : passing a dictionary

查看:58
本文介绍了Django视图:传递字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Django(来自CodeIgniter)开始,一切都很混乱...

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

我想按pub_date排序我的博客帖子,并希望将它们显示在按月+年分组的模板中.

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

我尝试了此操作,但显然无法正常工作...而且我对Python + Django的了解非常糟糕,以至于我不明白为什么不这样做.

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

推荐答案

您可以使用 重新组合标签.

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>

您现在的视图很简单:

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

现在,在您的 layout.html 中,您拥有:

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>

这篇关于Django视图:传递字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆