我一直在努力解决这个问题。我试图用分页实现Django搜索。分页有效,但当我尝试搜索某些内容时,我收到此错误:
Course matching query does not exist.
这是追溯:https://pastebin.com/jJp2hLUs
代码:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def pagination(request, data, num=10):
paginator = Paginator(data, num)
page = request.GET.get('page')
try:
courses = paginator.page(page)
except PageNotAnInteger:
courses = paginator.page(1)
except EmptyPage:
courses = paginator.page(paginator.num_pages)
index = courses.number - 1
max_index = len(paginator.page_range)
start_index = index - 5 if index >= 5 else 0
end_index = index + 5 if index <= max_index - 5 else max_index
page_range = paginator.page_range[start_index:end_index]
return courses, page_range
def search(request):
query = request.GET.get('q')
if query:
results = Course.objects.filter(Q(name__icontains=query))
else:
results = Course.objects.get()
pages = pagination(request, results, num=1)
context = {
'courses': pages[0],
'page_range': pages[1],
'query': query,
}
return render(request, 'courses/index.html', context)
def courses(request, slug):
query = Course.objects.get(slug=slug)
context = {'courses': Course.objects.filter(slug=slug),
'lectures': query.lectures.order_by('lecture_category'),
}
return render(request, 'courses/courses.html', context)
网址:
urlpatterns = [
path('', views.index, name='index'),
re_path('(?P<slug>[\w-]+)/', views.courses, name='courses'),
path('results/', views.search, name="search"),
]
答案 0 :(得分:1)
网址&#34; / results /&#34;匹配courses
的模式,以便调用视图。您应该交换订单,以便Django与文字字符串匹配&#34;结果&#34;第一
此外,如果您正在使用&#34;路径&#34;最好是保持一致并在整个过程中使用它 - Django包括一个&#34; slug&#34;输入新格式。所以:
urlpatterns = [
path('', views.index, name='index'),
path('results/', views.search, name="search"),
path('<slug:slug>/', views.courses, name='courses'),
]
最后,请注意您的结果网址并未捕获&#34; slug&#34;参数,所以你的观点不应该期望它,你不应该在搜索查询中使用它。