Django Rest Framework - 缺失静态目录
我最近在Digital Ocean上启动了一个服务器,里面预装了Ubuntu 14.04和Django。我想创建一个API,决定使用Django Rest Framework。我按照http://www.django-rest-framework.org/上的步骤安装了Django Rest Framework。
这是我在服务器上访问教程网站时的样子。
如你所见,这个页面看起来和Django Rest Framework教程网站上的样子不一样。这是因为当我查看我网站的源代码时,所有的/static/rest_framework/*
文件都出现了404错误,也就是找不到的意思。
这是我在Django项目根目录下的settings.py文件。
"""
Django settings for django_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7Vnib8zBUEV3LfacGKi2rT185N36A8svyq8azJLvNpv7BxxzMK'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
)
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'django_project.urls'
WSGI_APPLICATION = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'yj4SM6qcP0',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
有没有人能帮我解决这个缺少/static/rest_framework/的错误?如果我要为我的应用程序创建一个API,我希望它看起来好看一些。
如果你需要其他信息来帮助解决这个问题,请告诉我,非常感谢你的帮助。
9 个回答
如果你在用Heroku来托管你的网站,可以试试这个链接。对我来说是有效的。https://devcenter.heroku.com/articles/django-assets
总结一下:
- 如果你还没有静态文件夹,先创建一个。(把它放在和你的manage.py文件同一级别)
- 把Python包放到这个文件夹里(把这个文件夹复制到静态文件夹中 --> C:\Python37_64\Lib\site-packages\rest_framework)
- 把下面的代码添加到你的项目中。
settings.py
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
...
MIDDLEWARE_CLASSES = (
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
'whitenoise.middleware.WhiteNoiseMiddleware',
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
requirements.txt
...
#add whotrnoise to requirements
whitenoise
我做了这个好几次,快要疯了。我把DEBUG设置成了False。
在我的情况下,我是依靠Gunicorn来运行服务器的。我尝试按照之前的讨论更新我的settings.py
文件,但可惜的是,什么都没能解决我的问题。
最后,我在DRF的文档中反复琢磨,特别是这部分内容 https://docs.djangoproject.com/en/dev/howto/static-files/
我通过更新urls.py
文件解决了这个问题,具体做法如下。
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
然后我更新了settings.py
,具体如下。
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
现在执行 => python manage.py collectstatic
首先,你需要在Django的settings.py文件中设置静态文件的URL和静态根目录。
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
然后,收集所有的静态文件。
python manage.py collectstatic
我找到了解决我问题的方法!
经过一番费脑子的研究,我重新阅读了这个 Stack Overflow 问题,之前看它的时候感觉没什么帮助。
现在我在我的 django_project 文件夹里的 settings.py 文件看起来是这样的。
"""
Django settings for django_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'DwGCDqtcqzzGO2XK87u7bVSEUqHogZRFl4UdhkcCudSHxLUVvx'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
)
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'django_project.urls'
WSGI_APPLICATION = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'mpOQzpYFci',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_ROOT = '/home/django/django_project/django_project/static'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
我在 django_project 文件夹里,settings.py 文件旁边新建了一个名为 'static' 的文件夹,里面放了所有必要的资源,比如 'rest_framework' 和 'admin'。做完这些改动后,我重启了 gunicorn,然后重新加载了我的网页,结果成功了!
感谢那些试图帮助我的朋友们,你们确实让我朝着正确的方向前进,可能也让这个过程快了很多。