urls.py 无法直接在 Django 中
urls.py cannot direct in Django
我想在我的博客中创建列表类别并查看类别
这是view.py
def view_category(request, pk):
category = get_object_or_404(Category, pk=pk)
return render_to_response('blog/category_detail.html', {
'category': category,
'categories': Category.objects.all(),
'tags': Tag.objects.all(),
'posts': Post.objects.filter(category__id=pk)
})
def post_list(request):
posts = Post.objects.filter(published_date__isnull=False).order_by('published_date')
return render(request, 'blog/post_list.html', {
'posts': posts,
'categories': Category.objects.all(),
'tags': Tag.objects.all(),
})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
这是urls.py
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^post/all/$', views.post_list, name='index'),
url(r'^post/category/(?P<pk>[0-9]+)/$', views.view_category, name='view_blog_category'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail),
)
但我收到这样的错误
Exception Value: Reverse for 'view_blog_category' with arguments '()' and keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['post/category/(?P<pk>[0-9]+)/$']
这是线路错误:
{% for cat in categories %}
<li><a href="{% url 'view_blog_category' pk=category.pk %}">{{ cat.title }}</a></li>
{% endfor %}
所以,你能帮我找到解决这个问题的方法吗?
正如我在 中提到的,您使用了错误的变量。在url标签中使用cat.pk
,你的问题应该就解决了。
我想在我的博客中创建列表类别并查看类别
这是view.py
def view_category(request, pk):
category = get_object_or_404(Category, pk=pk)
return render_to_response('blog/category_detail.html', {
'category': category,
'categories': Category.objects.all(),
'tags': Tag.objects.all(),
'posts': Post.objects.filter(category__id=pk)
})
def post_list(request):
posts = Post.objects.filter(published_date__isnull=False).order_by('published_date')
return render(request, 'blog/post_list.html', {
'posts': posts,
'categories': Category.objects.all(),
'tags': Tag.objects.all(),
})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
这是urls.py
from django.conf.urls import patterns, include, url
from . import views
urlpatterns = patterns('',
url(r'^post/all/$', views.post_list, name='index'),
url(r'^post/category/(?P<pk>[0-9]+)/$', views.view_category, name='view_blog_category'),
url(r'^post/(?P<pk>[0-9]+)/$', views.post_detail),
)
但我收到这样的错误
Exception Value: Reverse for 'view_blog_category' with arguments '()' and keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['post/category/(?P<pk>[0-9]+)/$']
这是线路错误:
{% for cat in categories %}
<li><a href="{% url 'view_blog_category' pk=category.pk %}">{{ cat.title }}</a></li>
{% endfor %}
所以,你能帮我找到解决这个问题的方法吗?
正如我在 cat.pk
,你的问题应该就解决了。