开发者

Django url reverse and regular expression

开发者 https://www.devze.com 2023-03-31 05:02 出处:网络
I got this in my urlpatterns url(r\'^(page/(?P<page>\\d+)/)?$\', \'index\', name = \'index_path\')

I got this in my urlpatterns url(r'^(page/(?P<page>\d+)/)?$', 'index', name = 'index_path')

and here is my views.py file

def index(request, page=1):
    posts = Post.objects.filter(published = True)
    paginated_posts = Paginator(posts, 20)

    try:
        target_page = paginated_posts.page(page)
    except EmptyPage:
        return redirect(reverse('index_path'))

    response_dict = {
        'posts': target_page.object_list,
        'page': target_page,
        }

    return render(request, 'posts/index.html', response_dict)`

I use this for simple pagination, if user enters nothing ex '/blog/' return him/her first page, else return him/her page which he/she want.

Its working. But there is a problem when I want to use reverse() function.

When I type in interactive shell:

reverse("index_path")  

I got:

 '/blog/'

But I do this:

reverse("index_path", 开发者_如何学运维args=(1, ))

I got error which says:

NoReverseMatch: Reverse for 'index_path' with arguments '(1, )' and keyword arguments '{}' not found.

PS: in my master urls.py

url(r'^blog/', include('app.posts.urls')),


I think in order to make this work properly you'll have to have two urls:

url(r'^page/(?P<page>\d+)$', 'index', name = 'index_path_page'),
url(r'^$', 'index', name = 'index_path'),

Then when you reverse, you have two options:

reverse('index_path_page', args=[1])
# or
reverse('index', args=[1]) # pulls by the name of the view.

The second is not recommended, but could certainly lead to easier logic in places.


Consider the URL regular expression.

r'^(blog/(?P<page>\d+)/)?$'

(Assuming you meant blog/ rather than page/.)

This contains two groups.

  • (blog/(?P<page>\d+)/) which is unnamed and thus $1
  • (?P<page>\d+) which is named as "page".

You don't want to capture the first group there, so you should use (?:...) rather than (...).

So then, try using ^(?:blog/(?P<page>\d+)/)?$ as your match regular expression. Then, try reverse('index_path', kwargs={'page': 1}).

0

精彩评论

暂无评论...
验证码 换一张
取 消