Joff
Joff

Reputation: 12197

Django proper way to url redirect?

Say I had a blog type app and I wanted all URL requests to /blog to be redirected to /blog/1/ for pagination purposes...

Would I be correct in doing urls like this...

url(r'^blog/$', 'blog.views.redirect_to_main'),
url(r'^blog/(?P<page>[\d]+)/$', 'blog.views.main_page'),

Of course the redirect_to_main function just returns a redirect url to /blog/1/

I can't think of another way to do this and keep consistent URL's in my templates. Ideally I would like /blog and /blog/1/ to just go to the same view, but IDK how to reconcile the template links.

Does this look like the correct way?

EDIT (adding an example of the template links):

<div class='blog_sidebar_content'>
    <ul>
    {% for category in categories %}
        <a href='../../{{ category.slug }}'><li>{{ category }}</li></a>
        <ul>
            {% for subcategory in category.blogsubcategory_set.all %}
                <a href='../../{{ category.slug }}/{{ subcategory.slug }}'><li>{{ subcategory }}</li></a>
            {% endfor %}
    {% endfor %}
</div> 

Upvotes: 0

Views: 220

Answers (1)

starkshang
starkshang

Reputation: 8578

First,Replace

url(r'^blog/$', 'blog.views.redirect_to_main'),

with

url(r'^blog/$', 'blog.views.main_page'),

And in your parameter of method main_page,set the default page parameter to 1 so that when no page parameter is given,it will be 1.

Upvotes: 2

Related Questions