【写在前面】:
最近在做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