我正在使用Django进行简单搜索,并使用分页中的构建对结果进行分页,当我单击“下一步”以查看下一页结果时出现此错误,int()参数必须是字符串,类似于字节对象或数字,而不是“ NoneType” 我不知道是什么原因造成的,这是代码,q是查询字符串
def result(request):
try:
q = request.GET.get('q')
orders = Order.objects.filter(Q(flat_number=int(q)) | Q(customer_contact=int(q)))
paginator = Paginator(orders, 10) # Show 25 contacts per page
page = request.GET.get('page')
orders = paginator.get_page(page)
context['orders'] = orders
return render(request, 'main/results.html',context)
except Exception as e:
print('error is ', e)
return HttpResponse(str(e))
答案 0 :(得分:0)
在request.GET.get('q')
中,如果q没有作为get调用中的参数传递,它将返回None。
如果未传递q,将其更改为request.GET['q']
将引发异常
答案 1 :(得分:0)
这里是如何使用分页器模块(用于空白页面等)的示例。
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def post_list(request): #list items
queryset_list = Post.objects.all() #.order_by("-timestamp")
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query) |
Q(content__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 10) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "Building stuff with code",
"page_request_var" : page_request_var
}
return render(request, "post_list.html", context)
答案 2 :(得分:0)
以以下方式尝试
def result(request):
try:
q = request.GET.get('q')
orders = Order.objects.filter(Q(flat_number=int(q)) |
Q(customer_contact=int(q)))
paginator = Paginator(orders, 10) # Show 25 contacts per page
page = request.GET.get('page')
try:
pots = paginator.page(page)
except PageNotAnInteger:
posts = paginador.page(1)
except EmptyPage:
posts = paginador.page(1)
context['orders'] = post
return render(request, 'main/results.html',context)
except Exception as e:
print('error is ', e)
return HttpResponse(str(e))