django意见:通过一个字典 [英] django views : passing a dictionarry
问题描述
我从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);
这是我尝试一个对象:
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
,你有:
<ul>
{% for key,items in blogs.iteritems %}
<li>{{ key }}
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
这篇关于django意见:通过一个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!