Django URLS, how to map root to app?

后端 未结 7 978
迷失自我
迷失自我 2021-01-30 08:43

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 m

相关标签:
7条回答
  • 2021-01-30 08:55

    This sounds strange.

    Your latest attempt should work, but what I normally do - put

    urlpatterns = patterns('',
        (r'^$', lambda r: HttpResponseRedirect('myapp/')),
        ...
    )
    

    This scales better when you start adding new apps.

    0 讨论(0)
  • 2021-01-30 08:58

    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'),
    )
    
    0 讨论(0)
  • 2021-01-30 09:07

    I know the answer is late, but i had my fair share of hunting recently. This is what i tried with CBV.. in Project urls.py

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^$', include('app_name.urls', namespace='app_name')),
    ]
    

    PS: It is always recommended to use namespace. Gives a good advantage later on.

    In App urls.py

    urlpatterns = [
        url(r'^$', views.IndexPageView.as_view(), name='index'),
    ]
    
    0 讨论(0)
  • 2021-01-30 09:08

    old question here ... (as much as myself :o)
    but still worth of sharing updates for Django 3.x:

    In project urls.py just add:

    urlpatterns = [
        path('', include('myapp.urls')), 
        path('myapp/', include('myapp.urls')),
        #path('admin/', admin.site.urls),
    ]
    

    Be aware that this solution will monopolize the whole django to your hungry&selfish app :-) !!!

    0 讨论(0)
  • 2021-01-30 09:09

    As I didn't see any answer for django 2.0 I thought I'll provide one. you have to use '' as the root url. Here is an example from django 2.0 docs

    urlpatterns = [
        path('', main_views.homepage),
        path('help/', include('apps.help.urls')),
        path('credit/', include(extra_patterns)),
    ]
    
    0 讨论(0)
  • 2021-01-30 09:13

    Just put an empty raw regular expression: r''

    I tested here and it worked perfectly.

    urlpatterns = patterns('',
        url(r'', include('homepage.urls')),
        url(r'^homepage/', include('homepage.urls')),
        url(r'^admin/', include(admin.site.urls)),
    )
    

    Hope it help!

    0 讨论(0)
提交回复
热议问题