这可能是一个有点幼稚的问题,但我一直在尝试了解如何使用新的 Date Based views in django ,但没有一个例子,我在死胡同。我想要做的是在一个页面上显示我所有的博客条目(带有分页),并且在侧面导航中我想显示根据年份和月份完成的归档。
我想要的很基本,可以看下图。
如果有人可以给我一个例子,那就太好了。我可以处理模板,但只需要知道如何使用基于类的通用 View 。如果是通用 View ,我并没有真正使用太多。
最佳答案
最简单的例子:
views.py
from django.views.generic.dates import MonthArchiveView
from myapp.models import Article
urlpatterns = patterns('',
url(r'^articles/monthly/$',MonthArchiveView.as_view(
model=Article,
paginate_by=12,
date_field='publish_date',
template_name='archive_templates/monthly.html',
),name="monthly"),
)
您需要使用正确的日期和月份调用 View ,否则会出现异常。默认参数是 Y
格式的 year
和 b
格式的 month
(小写的短月份名称)。
调用示例articles/monthly/?year=2012&month=feb
这是您可以使用的示例 archive_templates/monthly.html
。
我正在使用优秀的 twitter bootstrap 中的 css 类框架。强烈推荐!
此代码段包含可用月份:
Archive for {{ month|date:"F" }} {{ month.year }}<br />
<div class="pagination pull-left">
<ul>
{% if previous_month %}
<li class="prev">
<a href="{% url monthly %}?year={{ previous_month|date:"Y" }}&month={{ previous_month|date:"b" }}">
← {{ previous_month|date:"M Y" }}
</a>
</li>
{% endif %}
{% if next_month %}
<li class="next">
<a href="{% url monthly %}?year={{ next_month|date:"Y" }}&month={{ next_month|date:"b" }}">
{{ next_month|date:"M Y" }} →</a>
</li>
{% endif %}
</ul>
</div>
{% endif %}
这个片段做了分页:
{% if is_paginated %}
<div class="pagination pull-right">
<ul>
<li class="{% if page_obj.has_previous %}prev {% else %} prev disabled {% endif %}">
<a href="{% if page_obj.has_previous %}?page={{ page_obj.previous_page_number }}&year={{ month|date:"Y" }}&month={{ month|date:"b" }}{% else %}#{% endif %}">←</a></li>
<li class="disabled"><a href="#"><strong>{{ page_obj.number }} of {{ paginator.num_pages }}</strong></a></li>
<li class="{% if page_obj.has_next %}next{% else %} next disabled {% endif %}">
<a href="{% if page_obj.has_next %}?page={{ page_obj.next_page_number }}&year={{ month|date:"Y" }}&month={{ month|date:"b" }}{% else %}#{% endif %}">→</a>
</li>
</ul>
</div>
{% endif %}
实际的对象列表很容易迭代:
<table class="zebra-striped" width="100%">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Author</th>
<th>Published On</th>
</tr>
</thead>
<tbody>
{% for obj in object_list %}
<tr>
<th>{{ forloop.counter }}</th>
<td>{{ obj.title }}</td>
<td>{{ obj.author }}</td>
<td>{{ obj.publish_date|date:"d/m/Y" }}</td>
</tr>
{% endfor %}
</tbody>
</table>
从这里你应该能够弄清楚如何开发你的存档菜单。
关于django - 如何在 Django 中使用基于日期的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9155852/