1

我以前在我网站的不同页面上建立了这样的档案。不过,这次Django似乎不想和我合作了。

class IndexView(ArchiveIndexView):
    template_name = 'cms/blog_base.html'
    date_field = 'pub_date'
    latest = '20'
    model = Entry

In template {% for year in date_list %} {{ year|date:"Y" }} gives me a date relating to none of my entries. {% for entry in object_list % } {{ entry.pub_date|date:"Y" }} obviously outputs the correct date for the entry but as the entries grow I can only imagine it will continue to duplicate the years and months.

那么我做错了什么?为了将日期与我的条目集相关联,我必须在 ArchiveIndexView 和模板标记中做什么?过去它们位于单独的页面上,因此被 url conf 中的正则表达式过滤。我看到的一个解决方案是使用一些原始 SQL 创建一个自定义管理器,这就是我正在看的?如果是这样,我将重新考虑这一切。提前感谢社区。

更新:示例:我在主页上想要的内容类似于此页面上的内容https://unweb.me/blog/monthly-archives-on-Django 我现在也在考虑尝试他们的解决方案就像一个不错的 UI/UX。但是,我是一个简单的人,如果有的话,我很想走简单的路线。

4

2 回答 2

3

您在寻找重组功能吗?

例子:

{% regroup object_list by date_field|date:"Y" as year_list %}
{% for year in year_list %}
    {% regroup year.list by date_field|date:"F" as month_list %}
    {% for month in month_list %}
        {{ month.grouper }} / {{ year.grouper }} <br />
        {{ month.list }}
    {% endfor %}
{% endfor %}
于 2012-09-28T06:14:29.057 回答
2

我从一个简短的博客教程在线找到了一个更好的解决方案,它实现了以下内容。我验证它是否有效。

def mkmonth_lst():
"""Make a list of months to show archive links."""
if not Post.objects.count(): return []

# set up vars
year, month = time.localtime()[:2]
first = Post.objects.order_by("created")[0]
fyear = first.created.year
fmonth = first.created.month
months = []

# loop over years and months
for y in range(year, fyear-1, -1):
    start, end = 12, 0
    if y == year: start = month
    if y == fyear: end = fmonth-1

    for m in range(start, end, -1):
        months.append((y, m, month_name[m]))
return months

def main(request):
"""Main listing."""
posts = Post.objects.all().order_by("-created")
paginator = Paginator(posts, 10)
try: page = int(request.GET.get("page", '1'))
except ValueError: page = 1

try:
    posts = paginator.page(page)
except (InvalidPage, EmptyPage):
    posts = paginator.page(paginator.num_pages)

return render_to_response("list.html", dict(posts=posts, user=request.user,
                                            post_list=posts.object_list,    months=mkmonth_lst()))

# The template info
    <div id="sidebar">
    Monthly Archive
    <p>
    {% for month in months %}
        {% ifchanged month.0 %} {{ month.0 }} <br /> {% endifchanged %}
        <a href="{% url blog.views.month month.0 month.1 %}">{{ month.2 }}</a> <br />
    {% endfor %}
    </p>
</div>

这将在您的主页上生成一个以年份分隔的列表,其中包含仅包含帖子的月份。

于 2012-10-10T22:06:55.987 回答