Django '/' only homepage url error

无人久伴 提交于 2019-12-07 02:02:59

问题


I am using Django 2.0 and now I have no idea how to make an 'empty' url for the homepage. Meaning, I want it to route for web.com/ or web.com. I tried this code but it does not work:

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

...and post.urls

urlpatterns = [
    path('', views.index, name='index')
]

And the error I get when I make a request to localhost:8000:

Request URL: http://localhost:8000/ Using the URLconf defined in myblog.urls, Django tried these URL patterns, in this order:

  1. admin/

  2. /

The empty path didn't match any of these.

I did sort of find a workaround by setting path to an empty string '' on both but I am not sure if it is recommended or what errors it might cause. Help is much appreciated. Thank you :-).


回答1:


You don't need "/" for Home url, just leave both the path with "". The home url 127.0.0.1:8000/ is nevertheless is same as 127.0.0.1:8000. This URL pattern will work for the home page.

urls.py

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

and posts.urls

urlpatterns = [
    path('', views.index, name='index')
]



回答2:


There are plenty of references to blank URL patterns in the Django 2.0 doccumentation.

Django 2.0 Docs URLs section

Furthermore, the slash you added on 'admin/' when viewing from browser is not required. The url dispatcher will strip the trailing slashes on your URL confs, but it wont be stripped on the Web request. This means it wont find a match in your case, try localhost:8000/admin



来源:https://stackoverflow.com/questions/48064071/django-only-homepage-url-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!