Python Django Rest Framework - 缺少静态目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25375448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:07:59  来源:igfitidea点击:

Django Rest Framework - Missing Static Directory

pythondjangodjango-rest-framework

提问by BigBerger

I have recently started a Digital Ocean server with a pre-installed Django image on Ubuntu 14.04. I wanted to create an API, and have decided on the Django Rest Framework. I installed the Django Rest Framework exactly according to http://www.django-rest-framework.org/.

我最近在 Ubuntu 14.04 上启动了一个带有预安装 Django 映像的 Digital Ocean 服务器。我想创建一个 API,并决定使用 Django Rest Framework。我完全按照http://www.django-rest-framework.org/安装了 Django Rest Framework 。

Here is what the tutorial site looks like when I access it on my server.

这是我在服务器上访问教程站点时的样子。

enter image description here

在此处输入图片说明

As you can see, it does not look like the site on the rest framework tutorial website. This is because of the fact that when I view the source code of my site, all of the /static/rest_framework/*files give me a 404 error.

如您所见,它看起来不像其余框架教程网站上的网站。这是因为当我查看我网站的源代码时,所有/static/rest_framework/*文件都给我一个 404 错误。

Here is my settings.py file in the Django 'django_project' root directory.

这是我在 Django '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 = '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.clickHymaning.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/'

Can anyone help me fix this missing /static/rest_framework/ location error? If I am going to have an API for my application I would like it to be a good looking one.

谁能帮我解决这个丢失的 /static/rest_framework/ 位置错误?如果我要为我的应用程序提供一个 API,我希望它看起来很漂亮。

Let me know if you need anything else to help you fix this, and thank you in advance for your help.

如果您需要其他任何东西来帮助您解决此问题,请告诉我,并提前感谢您的帮助。

采纳答案by BigBerger

I have found the solution to my problem!

我找到了解决我的问题的方法!

After much mind boggling research, I re-read thisstack overflow question that didn't seem to help me the last time I took a look at it.

经过大量令人难以置信的研究,我重新阅读了这个堆栈溢出问题,上次我看它时似乎没有帮助。

My new settings.py in my django_project folder now looks like this.

我的 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.clickHymaning.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'),
)

I now have a folder named 'static' right next to my settings.py file in my django_project folder with all necessary resources such as 'rest_framework' and 'admin'. I restarted gunicorn after this change and reloaded my web page and it worked!

我现在在我的 django_project 文件夹中的 settings.py 文件旁边有一个名为“static”的文件夹,其中包含所有必要的资源,例如“rest_framework”和“admin”。在此更改后,我重新启动了 gunicorn 并重新加载了我的网页,它起作用了!

Thanks to those of you who tried to help, you did lead me in the right direction and probably made this go by a lot faster.

感谢那些试图提供帮助的人,你们确实引导我朝着正确的方向前进,并且可能使这一切进展得更快。

回答by k80oshea

I was unable to get any of the above solutions to work on our webapp, but discovered that if the app can connect to an S3 bucket where it can access deployed static files, django rest_framework works pretty seemlessly (as discussed here). Here's the relevant code for our settings.py:

我无法让上述任何解决方案在我们的 web 应用程序上运行,但发现如果应用程序可以连接到可以访问部署的静态文件的 S3 存储桶,django rest_framework 可以无缝地工作(如这里所讨论的)。这是我们 settings.py 的相关代码:

    aws = pcfenv.get_service(label='aws-s3') # or however you are accessing your s3 bucket & credentials

    if aws is not None:
        keys = aws.credentials
        AWS_ACCESS_KEY_ID = keys["access_key_id"]
        AWS_SECRET_ACCESS_KEY = keys["secret_access_key"]
        AWS_STORAGE_BUCKET_NAME = keys["bucket"]
        AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
        AWS_S3_OBJECT_PARAMETERS = {
            'CacheControl': 'max-age=86400',
        }
        AWS_LOCATION = 'static'
        STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
        STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
        DEFAULT_FILE_STORAGE = 'mysite.storage_backends.MediaStorage'

    # static files
    STATIC_URL = '/static/'
    STATIC_ROOT = 'static/'

    # local storage
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    MEDIA_URL = '/media/uploads/'

You'll need to pip install the boto3and django-storagesdependencies for it all to work.

您需要 pip installboto3django-storages依赖项才能使其全部工作。

回答by Rajiv Sharma

First, You need to set static url and static root in django settings.py

首先,您需要在 django settings.py 中设置静态 url 和静态根

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static") 

Then collect all static files

然后收集所有静态文件

python manage.py collectstatic