结论:Django的path函数的路径存在一部分特殊的字符,诸如/static/xxx/等路径会强制转入后台文件区,而无法对其进行路径影射。
版本:Python 3.8;Django 4.1.12(2以上版本应该都差不多)
首先是Django的path函数基本写法(urls.py):
from django.urls import path
from ... import views
urlpatterns = [
# 固定url
path('articles/2003/', views.xxx),
# 单参数传入
path('articles/<int:year>/', views.xxx),
# 多参数传入
path('articles/<int:year>/<str:title>/', views.xxx),
]
然后是视图里的处理函数:
from django.shortcuts import render, redirect, ...
def some_view(request, year, title):
date = year
name = title
...
return render(request, ...)
按以上思路去写多半不会出错,但是问题在于,我将nodejs生成的静态资源(node_modules这些文件)用作后台资源,包括html的资源引用路径我都不想改,所以只能增改settings.py里面的模板路径以及html的根路径(base标签),然后改完了发现有些路径比如“http://127.0.0.1:8000/static/coreui/dist/index.html”必须正常映射到“http://127.0.0.1:8000/index/”,否则会产生很多bug。
于是,我就写了这样的代码:
from django.contrib import admin
from django.urls import path
from xxx import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
path('index/', views.index),
path('static/coreui/dist/<str:html>/', views.shift),
path('static/coreui/dist/<str:html>/', views.shift) 无论如何都会出错。
我检查了很多遍,网上的各种教程也没有细说这一点,直到我尝试把/static改成其他路径,才发现以/static开头的路径应该都是无法强制跳转的。
如果要启用django的static静态文件,实际上很复杂,首先要在settings.py中如下设置(staticfiles这个目录疑似是没有任何用处)
STATIC_URL = '/static/'
if not DEBUG:
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "staticfiles"),
]
else:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
在urls.py中添加如下代码:
from django.urls import path, re_path
from django.conf import settings
from django.views.static import serve
from . import views
urlpatterns += [
re_path(r'^static/(?P<path>.*)$', serve, {'document_root': settings.STATIC_ROOT}, name='static'),
]
在开发环境下,要运行python manage.py collectstatic来访问这些静态资源。
参考: