在settings文件中:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static/"),
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static_new/")
# 注意:STATIC_ROOT 不能和 STATICFILES_DIRS重复
MEDIA_URL = "/media/"
# media配置,用户上传的文件都默认放在这个文件夹下
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
static
和media
两部分from django.views.static import serve
url(r'^static/(?P.*)$', serve, {"document_root": settings.STATIC_ROOT}),
url(r'^media/(?P.*)$', serve, {"document_root": settings.MEDIA_ROOT}),
CSRF_TRUSTED_ORIGINS
配置,并将你的域名添加进去:CSRF_TRUSTED_ORIGINS = [
'http://www.xxxx.com', # 添加你的域名
'https://www.xxxx.com' # 如果使用 HTTPS 协议,则也需要加上
]
ALLOWED_HOSTS
,也可以在同一个文件里添加或更新它,以确保 Django 允许该域名访问:ALLOWED_HOSTS = [
'www.xxxxx.com',
'xxxx.com' # 如果需要无 www 前缀的访问
'*' # 允许任何主机访问
]
安装corsheaders
pip install django-cors-headers
配置settings
INSTALLED_APPS = [
'xxxxxxxx',
'dxxxxxx',
'xxxxxxxx',
'xxxx',
'corsheaders',# 注册app corsheaders
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', # 加入中间键 位置必须在这里 不能在其他位置
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware', 如果你的项目没有考虑到 csrf 网络攻击,可注释掉,否则会报错没有传递 csrf cookie
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 具体情况可以更具实际需求来配置
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_HEADERS = '*'