gersande
gersande

Reputation: 463

Django urls.py and views.py behaviour -

I'm currently experimenting with Django and creating apps following the tutorials on the official website.

So my urls.py looks like:

urlpatterns = patterns('',
    (r'^/$','ulogin.views.index'), #why doesn't this work?
    (r'^ucode/$', 'ulogin.views.index'),
    (r'^ucode/(\d+)/$', 'ulogin.views.index'),
)

And my views.py looks like:

def index(request):
    return HttpResponse("Hello, world. You're at the poll index.")

def redirect_to_index(request):
    return HttpResponseRedirect('/ucode/')

When I run the server to check the test url, http://127.0.0.1:8000/ucode displays "Hello, world...etc" correctly, and works just fine. I've been messing with urls.py but I don't know how to get http://127.0.0.1:8000/ to display ulogin.views.index.

Upvotes: 1

Views: 125

Answers (2)

karthikr
karthikr

Reputation: 99660

First of all, for the pattern to match

(r'^/$','ulogin.views.index')

Should be

(r'^$','ulogin.views.index')

Also, trying to match the following URL would raise errors

(r'^ucode/(\d+)/$', 'ulogin.views.index'), 

because there is no view method that takes \d+ as a parameter.

The fix i recommend is:

(r'^ucode/(<?P<id>[\d]+)/$', 'ulogin.views.index'),

and then

def index(request, id=None):
    return HttpResponse("Hello, world. You're at the poll index.")

You can read more about named URL groups here

Upvotes: 2

Nafiul Islam
Nafiul Islam

Reputation: 82550

It does not work because the root of a web-server when it comes to django urls is characterized by the empty string, like so -> ^$. So, just change ^/$ to ^$, and it will work.

Upvotes: 2

Related Questions