piperck
piperck

Reputation: 75

About django url why will be overwrite?

IT's my file tree

____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

and about root urls.py file it's about

url(r'^dealwith_Time/$',include('dealwith_Time.urls')),
url(r'^dealwith_Time/12$',include('dealwith_Time.urls')),

and deal with_Time's urls are

url(r'^$', 'dealwith_Time.views.current_datetime'),
url(r'^/12$', 'dealwith_Time.views.hour_ahead'),

and show my deal with_Time's views

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")

the question is when I access the localhost:8000/dealwith_time it worked.and response the time .but when I access the localhost:8000/dealwith_time/12 .it's still response the time !and use the views's current_time function Rather than use hour_ahead function and print "victory".....why i so confused please help me ..

Upvotes: 1

Views: 47

Answers (2)

Domen Blenkuš
Domen Blenkuš

Reputation: 2242

You have $ signs at the end of urls in root's urls.py. That means that url has to match exactly (not just beginning). So in your example url matches to second entry in root's urls.py and empty string is passed to with_Time's urls.py so it will match first entry and display time.

If you are including other urls files you normally want to use regex without $, so it will match the beginning of url and remaining will be passed to included urls file.

To correct your example use this for root's urls.py:

url(r'^dealwith_Time/',include('dealwith_Time.urls')),

note that I've removed $, so /dealwith_time/12 and /dealwith_time/ will be both matched and 12 in first case will be passed to the next level.

And use this for with_Time's urls.py:

url(r'^$', 'dealwith_Time.views.current_datetime'),
url(r'^12$', 'dealwith_Time.views.hour_ahead'),

note that I've removed / in second line as it will be stripped in root's urls.py.

Upvotes: 1

rafaelc
rafaelc

Reputation: 59264

You have to change

url(r'^dealwith_Time/$',include('dealwith_Time.urls')),

for

url(r'^dealwith_Time/',include('dealwith_Time.urls')),

The $ sign overrides dealwith_Time/12 and would override anything that came after the foward slash sign.

Take a look at Regular Expressions.

Upvotes: 1

Related Questions