django3.urls用法

丁翊歌
2023-12-01

url是Django 1.x中的写法。
在Django2.1中,舍弃Django1.x中的url写法。
在Django2.x中,描写url配置的有两个函数path和re_path。re_path()函数可以看做是django 1.x中得url函数,即可以在路径中使用正则。

Django文档说明https://docs.djangoproject.com/en/3.2/ref/urls/

1、path()
path( route , view , kwargs=None , name=None )
返回一个包含在 中的元素urlpatterns。
例如:

from django.urls import include, path

urlpatterns = [
    path('index/', views.index, name='main-view'),
    path('bio/<username>/', views.bio, name='bio'),
    path('articles/<slug:title>/', views.article, name='article-detail'),
    path('articles/<slug:title>/<int:section>/', views.section, name='article-section'),
    path('weblog/', include('blog.urls')),
    ...
]

2、re_path()
re_path( route , view , kwargs=None , name=None )
返回一个包含在 中的元素urlpatterns。
例如:

from django.urls import include, re_path

urlpatterns = [
    re_path(r'^index/$', views.index, name='index'),
    re_path(r'^bio/(?P<username>\w+)/$', views.bio, name='bio'),
    re_path(r'^weblog/', include('blog.urls')),
    ...
]

3、include()
include( (pattern_list , app_namespace) , namespace=None )
参数:
模块– URLconf 模块(或模块名称)
namespace ( str ) – 包含的 URL 条目的实例命名空间
pattern_list –path()和/或re_path()实例的可迭代。
app_namespace ( str ) – 包含的 URL 条目的应用程序命名空间。
4、static()
static.static(前缀, view=django.views.static.serve , **kwargs )

rom django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
 类似资料: