当前位置: 动力学知识库 > 问答 > 编程问答 >

Why can't Django reverse this url regex that takes one optional parameter?

问题描述:

I have an app namespaced under blog in my root url conf:

urlpatterns = patterns('',

url(r'^blog/', include('blog.urls', namespace='blog')),

)

This is the regex I have for the blog index under blog.urls:

urlpatterns = patterns('',

url(r'^(?:(?P<page_num>\d+)/)?$', views.index, name='index'),

)

And here's my blog index view:

def index(request, page_num):

if not page_num:

return redirect('blog:index', args=[1])

post_list = Post.objects.all()

p = Paginator(post_list, 10)

try:

posts = p.page(page_num)

except PageNotAnInteger:

posts = p.page(1)

except EmptyPage:

posts = p.page(p.num_pages)

return render(request, 'blog/index.html', { 'post_list': posts })

Basically, what I'd like is to have the url redirect to /blog/1/ when you navigate to /blog/, which is why I've made page_num optional. And, of course going to /blog/n/ where n is in p.page_range should navigate to the appropriate pagination page.

However, when I go to /blog/ or /blog/1/, nothing loads, and eventually Django gives me the "No data received" error. I get the feeling that I'm writing my regex incorrectly, but I've tried a number of permutations and haven't had any luck (most give me the "Page not found" error).

I've also tried this pattern in the official Django docs, i.e. specifying this in blog.urls:

urlpatterns = patterns('',

url(r'^$', views.index, name='index'),

url(r'^(?<page_num>\d+)/$', views.index, name='index'),

)

And this in my blog index view:

def index(request, page_num=1):

....(the rest the same as above)...

But that gives me the following error when I navigate to /blog/:

TypeError at /blog/

index() takes exactly 2 arguments (1 given)

And the "No data received" error when I go to /blog/1/.

网友答案:

The view function page_num attribute doesn't have a default value so it is not optional. Change:

def index(request, page_num):

to

def index(request, page_num=None):

As a side note. You should probably also change the code:

if not page_num:

to

if page_num is None:

That is more explicit. Otherwise there are multiple different values that will trigger the redirect, for example 0.

分享给朋友:
您可能感兴趣的文章:
随机阅读: