我在 django 通用 object_list 函数的分页上遇到了一些麻烦,它并没有真正“聪明”到足以弥补我的愚蠢。
我正在尝试使用页码和类别的可选参数列出一个 url。urls.py 中的 url 如下所示:
url(r'^all/(?:(?P<category>[-\w]+)/page-(?P<urlpage>\d+))?/$',
views.listing,
),
category 和 urlpage 参数是可选的,因为额外的 "(?: )?" 在他们周围,效果很好。views.listing 是一个看起来像这样的包装函数(我认为这不是我的问题发生的地方):
def listing(request,category="a-z",urlpage="1"):
extra_context_dict={}
if category=="a-z":
catqueryset=models.UserProfile.objects.all().order_by('user__username')
elif category=="z-a":
catqueryset=models.UserProfile.objects.all().order_by(-'user__username')
else:
extra_context_dict['error_message']='Unfortunately a sorting error occurred, content is listed in alphabetical order'
catqueryset=models.UserProfile.objects.all().order_by('user__username')
return object_list(
request,
queryset=catqueryset,
template_name='userlist.html',
page=urlpage,
paginate_by=10,
extra_context=extra_context_dict,
)
在我的模板 userlist.html 中,我的链接看起来像这样(这是我认为真正的问题所在):
{%if has_next%}
<a href=page-{{next}}>Next Page> ({{next}})</a>
{%else%}
链接没有替换我的 url 中的 page 参数,而是向 url 添加了另一个 page 参数。网址最终看起来像这样“/all/az/page-1/ page-2/
发生这种情况并不奇怪,但是没有将 page 作为可选参数实际上可以工作,并且 Django 替换了 url 的旧页面部分。
我更喜欢这个 DRYer(至少我这么认为)解决方案,但似乎无法让它工作。任何提示如何使用更好的 urls.py 或模板标签来解决这个问题将不胜感激。
(也请原谅非母语英语和即时翻译的代码。任何关于这是一个好的或无根据的堆栈溢出问题的反馈也很乐意接受)