Learning how create regex URLCONF route in Django 1.3


Few developers complaining about hard to create url routes in Django. Regex always like nightmare, but we must get along with it. And don’t worry, in Django 1.3, you doesn’t need to know whole knowledge about regex. Meanwhile, design url usually common and not to complicate.

Know we see this example of URLCONF :

1
2
3
4
5
6
from django.conf.urls.defaults import patterns

urlpatterns = patterns(
    ”,
    (r’^posts/$’, ‘posts.views.index’),
)

First thing we should know
We know that Django search python module and search urlpatterns (a Python list) variable when processing request. So, we need to import patterns from django.conf.urls.defaults and create urlpatterns variable (list).

About r
We see “r” in “(r’^posts/$’, ‘posts.views.index’),”. What it is ? Actually, “r” will tell python that a string is raw. Which mean there no string should be escaped.

For instance, we know that ‘t’ refers to TAB. But, if we add r’t’ it will meaning backslash () and t. It will literally t and NOT TAB.

Common pattern
When creating route, it have common pattern (ignore the dots ……)

End with slash :

1
r’^ ……… /$’

Not end with slash:

1
r’^ ……… $’

If I want to route http://localhost:8000/posts into views index(), so I just create :

1
(r’^posts/$’, ‘posts.views.index’),

In case you need fast posts.views.index :

1
2
3
4
from django.http import HttpResponse

def index(request):
        return HttpResponse("Hello world!")

Remember to add comma in last route, because we need urlpatterns as list 🙂

Static integer or string
So, what happen if we want to create route “http://localhost:8000/posts/2003” or “http://localhost:8000/posts/sample” , so we create :

1
2
(r’^posts/sample/$’, ‘posts.views.index’),
(r’^posts/2003/$’, ‘posts.views.index’),

Knowing more …
We need to create archive posts like “http://localhost:8000/archives/2003/03” or “http://localhost:8000/archives/2004/03”, so we create :

1
(r’^archives/(d{4})/(d{2})/$’, ‘posts.views.archives’)

In case you need fast archives views :

1
2
3
4
5
6
7
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello world!")

def archives(request, *args):
    return HttpResponse(args)

The main key here is “(d{4})”. What is mean? To grab value in URL, we need to use parenthesis (). Then, we see that “/archives/2003/03” mean “archives//” so that why we need “d”. To limit into 4 integer only, we use “{4}” or to limit into 2 integer only, we use “{2}”. So, if we combine them, it will be :

1
2
(d{4})
(d{2})

Or use “(d+)” for unlimited number.

For string alpha lowercase (a-z) url patterns, you can use “([a-z]+)”, for instance :

1
(r’^archives/([a-z]+)/(d+)/$’, ‘posts.views.archives’),

Or maybe you need alphanumeric (capital and lower) with symbol like dash, underscore that usually need for slug :

1
(r’^archives/([a-zA-Z0-9_-]+)/(d+)/$’, ‘posts.views.archives’),

More advanced with named groups
Now we will learn how to set named groups on urlconf which will pass it values as keyword in views ( we use **kwargs ). To create named groups, use format (?Ppattern), for example :

1
(r’^read/(?P<month>d{4})/(?P<day>d{2})/$’, ‘posts.views.archives’)

And add views :

1
2
def read(request, **kwargs):
    return HttpResponse(str(kwargs[‘month’]))

With named groups, we received url variable as dictionaries.

URLCONF search against
URLCONF search against the request URL as a normal Python string with not include GET, POST or domain name. For instance, if “http://localhost:8000/read/” requested, it will search “read/”. Another, “http://localhost:8000/read/?page=2” will search “read/”.

The URLconf doesn’t look at the request method. In other words, all request methods — POST, GET, HEAD, etc. — will be routed to the same function for the same URL.

Passing extra options
We can passing parameters (dictionary) to views, for example :

1
(r’^archives/(d{4})/(d{2})/$’, ‘posts.views.archives’)

Change to :

1
(r’^archives/(d{4})/(d{2})/$’, ‘posts.views.archives’, {‘id’: ‘1’})

And you can read it dictionaries in views, for example :

1
2
def archives(request, *args, **kwargs):
    return HttpResponse(kwargs[‘id’])

Another must read reference :
Understanding Args & Kwargs : http://basicpython.com/understanding-arguments-args-and-kwargs-in-python/


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.