Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django URLS, how to map root to app?

I am pretty new to django but experienced in Python and java web programming with different frameworks. I have made myself a nice little django app, but I cant seem to make it match www.mysite.com as opposed to www.mysite.com/myapp.

I have defined urls and views in my urls.conf which is currently not decoupled from the app (don't mind that).

urlpatterns = patterns('myapp.views',   (r'^myapp/$', 'index'),   (r'^myapp/(?P<some_id>\d+)/global_stats/$', 'global_stats'),   (r'^myapp/(?P<some_id>\d+)/player/(?P<player_id>\d+)/$', 'player_stats'), ) 

All this works like a charm. If someone goes to www.mysite.com/myapp they will hit my index view which causes a http redirect to my "correct" default url.

So, how can I add a pattern that will do the same as (r'^myapp/$', 'index') but without the /myapp--that is, www.mysite.com should suffice?

I would think this would be very basic stuff... I tried adding a line like:

(r'^$', 'index'), 

however this throws me in a loop...

Hope you django gurus out there can clarify this for me!

like image 454
Hoof Avatar asked Sep 28 '11 08:09

Hoof


People also ask

How can we do URL mapping in Django?

Now, start the server and enter localhost:8000/hello to the browser. This URL will be mapped into the list of URLs and then call the corresponding function from the views file. In this example, hello will be mapped and call hello function from the views file. It is called URL mapping.

How do I change the root URL in Django?

A quick way is to include the projects url patterns at the new path. At the bottom of the main urls.py include the base_patterns at the new path.

How do I reference a URL in Django?

Django offers a way to name urls so it's easy to reference them in view methods and templates. The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py .

How does URL routing work in Django?

URL routing flow As we can see, the user enters a URL in the search bar of the web browser. Then, that URL is passed to the url.py file where it tries to find a matching URL pattern. If a matching URL is found, the corresponding view function attached with that URL is invoked. Otherwise, it returns 404 .


1 Answers

I know that this question was asked 2 years ago, but I've faced the same problem and found a solution:

In the project urls.py:

urlpatterns = patterns('',     url(r'^', include('my_app.urls')), #NOTE: without $ ) 

In my_app.urls.py:

urlpatterns = patterns('',     url(r'^$', 'my_app.views.home', name='home'),     url(r'^v1/$', 'my_app.views.v1', name='name_1'),     url(r'^v2/$', 'my_app.views.v2', name='name_2'),     url(r'^v3/$', 'my_app.views.v3', name='name_3'), ) 
like image 157
Kamal Alseisy Avatar answered Sep 28 '22 02:09

Kamal Alseisy