Django urls.py and views.py behaviour -

谁都会走 提交于 2019-12-10 11:41:45

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/17814378/django-urls-py-and-views-py-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!