关于django url为什么会被覆盖?
这是我的文件树关于django url为什么会被覆盖?,django,python-2.7,django-urls,Django,Python 2.7,Django Urls,这是我的文件树 ____mysite |____db.sqlite3 |____dealwith_Time | |______init__.py | |______init__.pyc | |____admin.py | |____admin.pyc | |____migrations | | |______init__.py | | |______init__.pyc | |____models.py | |____models.pyc | |____tests.py
____mysite
|____db.sqlite3
|____dealwith_Time
| |______init__.py
| |______init__.pyc
| |____admin.py
| |____admin.pyc
| |____migrations
| | |______init__.py
| | |______init__.pyc
| |____models.py
| |____models.pyc
| |____tests.py
| |____urls.py
| |____urls.pyc
| |____views.py
| |____views.pyc
|____manage.py
|____mysite
| |______init__.py
| |______init__.pyc
| |____settings.py
| |____settings.pyc
| |____urls.py
| |____urls.pyc
| |____wsgi.py
| |____wsgi.pyc
关于根URL.py文件
url(r'^dealwith_Time/$',include('dealwith_Time.urls')),
url(r'^dealwith_Time/12$',include('dealwith_Time.urls')),
和处理时间的网址是
url(r'^$', 'dealwith_Time.views.current_datetime'),
url(r'^/12$', 'dealwith_Time.views.hour_ahead'),
展示我对时代观点的看法
def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body> It is now %s.</body></html>" %now
return HttpResponse(html)
def hour_ahead(request):
return HttpResponse("victory")
def current_datetime(请求):
now=datetime.datetime.now()
html=“现在是%s.%”
返回HttpResponse(html)
提前def小时(请求):
返回HttpResponse(“胜利”)
问题是当我访问localhost:8000/dealand\u time
时,它工作了。并且响应了时间。但是当我访问localhost:8000/dealand\u time/12
时,仍然是响应时间!使用视图的当前时间功能,而不是使用hour\u-ahead
功能并打印“victory”
…为什么我如此困惑请帮助我….您必须更改
url(r'^dealwith_Time/$',include('dealwith_Time.urls')),
为了
$符号覆盖处理时间/12
,并将覆盖前斜杠符号之后的任何内容
看看。您在
根目录的url.py中的URL末尾有$
符号。这意味着url必须完全匹配(而不仅仅是开始)。因此,在您的示例中,url与root
的urls.py中的第二个条目匹配,空字符串通过\u Time
的urls.py传递给,因此它将匹配第一个条目和显示时间
如果包含其他url文件,则通常希望在不使用$
的情况下使用正则表达式,因此它将匹配url的开头,剩余的将传递给包含的url文件
要更正您的示例,请将其用于根的url.py
:
url(r'^dealwith_Time/',include('dealwith_Time.urls')),
url(r'^$', 'dealwith_Time.views.current_datetime'),
url(r'^12$', 'dealwith_Time.views.hour_ahead'),
请注意,我已经删除了$
,因此/dealand\u time/12
和/dealand\u time/
都将匹配,并且第一种情况下的12
将传递到下一个级别
并将其用于和\u Time
的url.py
:
url(r'^dealwith_Time/',include('dealwith_Time.urls')),
url(r'^$', 'dealwith_Time.views.current_datetime'),
url(r'^12$', 'dealwith_Time.views.hour_ahead'),
请注意,我已经删除了第二行中的/
,因为它将在root的url.py
ok中被剥离。我知道。就像root的url.py必须匹配我的交易时间的url.py中的两行代码一样。若第一行可以精确匹配,并且传递了空字符串,那个么我就可以看到时间了?