我得到NoReverseMatch at /
:
反向'类别'有论据'(u'',)'和关键字参数' {}'未找到。尝试了1种模式:['类别/(?P [\ w \ - ] +)/ $']
我不知道哪里出错了。我知道它在哪里造成但我不知道为什么。此网址导致错误:
url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.category, name='category'),
并且错误来自此index.html
{% for category in categories %}
<li class="list-group-item"><a href="{% url 'category' category.slug %}">{{ category.name }}</a></li>
{% endfor %}
我很确定我的views.py没有任何问题,但万一我会在这里发布
#for front page
def index(request):
"""This view return index page. In index page, there is thread list.
And thread list can be sorted by score, number of comment, date, title using paging.
GET parameters are 'sort' and 'page'. 'sort' is sorting methods. 'page' is number of page.
:param request: Django request object
:return: Thread list page
"""
categories = Category.objects.all()
try:
sort = request.GET["sort"].strip()
sort_method = SortMethods[sort]
page = request.GET["page"].strip()
except KeyError:
sort_method = SortMethods.score
page = 1
if sort_method == SortMethods.date:
thread_list = Post.objects.order_by("-pub_date")
else:
thread_list = Post.objects.all()
thread_list = sorted(thread_list, key=lambda x: x.get_score(), reverse=True)
paginator = Paginator(thread_list, 30)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context = {
"posts": posts,
"pages": paginator.page_range,
"sort": sort_method.name,
"categories":categories
}
return render(request, "main/index.html", context)
#for single-post page
def post(request, slug):
single_post = get_object_or_404(Post, slug=slug)
single_post.views += 1 # increment the number of views
single_post.save() # and save it
context_dict = {
'single_post' :single_post,
}
return render(request, 'main/post.html', context_dict)
#for category page
def category(request, category_name_slug):
try:
category = Category.objects.get(slug=category_name_slug)
sort = request.GET["sort"].strip()
sort_method = SortMethods[sort]
page = request.GET["page"].strip()
except KeyError:
sort_method = SortMethods.score
page = 1
if sort_method == SortMethods.date:
thread_list = Post.objects.filter(category=category).order_by("-pub_date")
else:
thread_list = Post.objects.filter(category=category)
thread_list = sorted(thread_list, key=lambda x: x.get_score(), reverse=True)
paginator = Paginator(thread_list, 30)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context = {
"posts": posts,
"pages": paginator.page_range,
"sort": sort_method.name,
"categories":category,
"cat_name_slug":category_name_slug,
}
return render(request, "main/index.html", context)
答案 0 :(得分:0)
首先要注意的是你有一个空slu :
反向&#39;类别&#39;使用参数&#39;(u&#39;&#39;,)&#39; 和关键字参数&#39; {}&#39;找不到
一个问题是如何定义categories
- .all()
是一种方法,称之为:
categories = Category.objects.all()
HERE^
此外,您应该检查您的类别是否已生成非空slu ..