python3.7.4+Django2.2.6一直提示path404报错问题:“Using the URLconf defined in XXX.urls, Django tried this...”
【寫在前面】:
最近在做python+Django做路徑開發時一直被路由設置中的path路徑設置所困擾,抽空把自己遇到的一些坑的解決方案一起和大家分享一下,歡迎大家評論區交流;
【Django應用工作原理】:
Django 如何處理一個請求?
當一個用戶請求Django 站點的一個頁面,下面是Django 系統決定執行哪個Python 代碼使用的算法:
-
Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has a urlconf attribute (set by middleware), its value will be used in place of the ROOT_URLCONF setting.
-
Django loads that Python module and looks for the variable
urlpatterns. This should be a Python list of django.urls.path()
and/or django.urls.re_path() instances. -
Django依次匹配每個URL 模式,在與請求的URL 匹配的第一個模式停下來。
-
Once one of the URL patterns matches, Django imports and calls the given view, which is a simple Python function (or a class-based view). The view gets passed the following arguments:
-
一個 HttpRequest 實例。
-
If the matched URL pattern returned no named groups, then the matches from the regular expression are provided as positional arguments.
-
The keyword arguments are made up of any named parts matched by the path expression, overridden by any arguments specified in the optional kwargs argument to django.urls.path() or django.urls.re_path().
-
If no URL pattern matches, or if an exception is raised during any point in this process, Django invokes an appropriate error-handling view. See Error handling below.
【path函數官方說明】:
函數 path() 具有四個參數,兩個必須參數:route 和 view,兩個可選參數:kwargs 和 name。現在,是時候來研究這些參數的含義了。 -
path() 參數: route?
route 是一個匹配 URL 的準則(類似正則表達式)。當 Django 響應一個請求時,它會從 urlpatterns 的第一項開始,按順序依次匹配列表中的項,直到找到匹配的項。
這些準則不會匹配 GET 和 POST 參數或域名。例如,URLconf 在處理請求 https://www.example.com/myapp/時,它會嘗試匹配 myapp/ 。處理請求 https://www.example.com/myapp/?page=3 時,也只會嘗試匹配 myapp/。
- path() 參數: view?
當 Django 找到了一個匹配的準則,就會調用這個特定的視圖函數,并傳入一個 HttpRequest 對象作為第一個參數,被“捕獲”的參數以關鍵字參數的形式傳入。稍后,我們會給出一個例子。
- path() 參數: kwargs?
任意個關鍵字參數可以作為一個字典傳遞給目標視圖函數。本教程中不會使用這一特性。
- path() 參數: name?
為你的 URL 取名能使你在 Django 的任意地方唯一地引用它,尤其是在模板中。這個有用的特性允許你只改一個文件就能全局地修改某個 URL 模式。
當你了解了基本的請求和響應流程后,請閱讀 教程的第 2 部分 開始使用數據庫.
【錯誤提示】:
【解決方案】
- 有問題的path配置
:
urlpatterns = [path('admin/', admin.site.urls),path('myapp/', views.register, name='register'), ]- 修改方法
# path('myapp/', views.register, name='register')# 問題路徑修改為以下兩種方式 path(r'', views.register, name='register') # 修改方式1 path('', views.register, name='register') # 修改方式2通過url路由配置實現不同網頁之間的切換操作詳見:https://blog.csdn.net/weixin_44322778/article/details/102550161
總結
以上是生活随笔為你收集整理的python3.7.4+Django2.2.6一直提示path404报错问题:“Using the URLconf defined in XXX.urls, Django tried this...”的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Django(一):项目中urls.py
- 下一篇: Python之web开发(六):pyth