Django urls.py和views.py行为 - [英] Django urls.py and views.py behaviour -
问题描述
我正在实验Django,并按照官方网站上的教程创建应用程序。
所以我的 urls.py
看起来像:
urlpatterns = patterns('',
(r'^ / $','ulogin.views.index'),#why这不工作?
(r'^ ucode / $','ulogin.views.index'),
(r'^ ucode /(\d +)/ $','ulogin.views.index'),
)
我的views.py看起来像:
$ {code} def index(request):
return HttpResponse(Hello,world。你在投票索引)
def redirect_to_index (请求):
返回HttpResponseRedirect('/ ucode /')
当我运行服务器检查测试URL, http://127.0.0.1:8000/ucode
正确显示Hello,world ... etc,并且工作正常。我一直搞乱urls.py,但我不知道如何获得 http://127.0.0.1:8000/
来显示ulogin.views.index。
首先,为了匹配的模式
(r'^ / $','ulogin.views.index')
应该是
(r'^ $','ulogin.views.index')
此外,尝试匹配以下网址会引发错误
(r'^ ucode /(\d +)/ $','ulogin.views.index'),
因为没有视图方法将 \d +
作为参数。
我建议的修正是:
(r'^ ucode /(<?P< id> \\)/ $','ulogin.views.index'),
然后
def index(request,id = None):
return HttpResponse(Hello,world。投票指数)
您可以阅读有关 named URL groups here
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.
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
这篇关于Django urls.py和views.py行为 - 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!