URL request -> view calling
同时,django又提供了另一种解析方式 - Reverse resolution of URLs它的解析过程为 view calling -> URL request
url(r'^category/(?P<cat_name>\w+)/$', 'category', name='list_category'),这样category的名字会被当做参数传递给
category
这个view.同时给这条url规则命名为list_category
.模板文件中,生成导航条的代码如下<nav id="site-nav">
{% for name in cat_all %}
<a name="{{ name }}" href="{% url 'list_category' name %}"
class="{% if name == cat_now %}active{% endif %}">{{ name|capfirst }}</a>
{% endfor %}
</nav>
url(r'^category/(?P<cat_name>\w+)/page/(?P<page_num>\d+)/$', 'category', name='page')分页显示的模板代码
{% if posts.object_list and posts.paginator.num_pages > 1 %}
<footer>
{% if posts.has_previous %}
<a href="{% url 'page' cat_now posts.previous_page_number %}"><</a>
{% endif %}
<span>
{{ posts.number }} of {{ posts.paginator.num_pages }}
</span>
{% if posts.has_next %}
<a href="{% url 'page' cat_now posts.next_page_number %}">></a>
{% endif %}
</footer>
{% endif %}
from django.shortcuts import render
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from blog.models import Post, Category
def category(request, cat_name, page_num=1):
if cat_name.lower() == 'home':
posts = Post.objects.all().order_by('-date')
else:
posts = Post.objects.all().filter(category__name=cat_name).order_by('-date')
paginator = Paginator(posts, 3)
try:
page = int(page_num)
except ValueError:
page = 1
try:
posts = paginator.page(page)
except (InvalidPage, EmptyPage):
posts = paginator.page(paginator.num_pages)
return render(request, 'blog/index.html',
{
'posts': posts,
'cat_now': cat_name,
'cat_all': map(lambda cat: cat.name, Category.objects.all())
})
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。