【问题标题】:Access the Django-Rest-Framework url do not load the styles file访问 Django-Rest-Framework url 不加载样式文件
【发布时间】:2018-08-21 14:32:15
【问题描述】:

我有一个settings.py 的项目:

# -*- coding: utf-8 -*-

"""
Django settings for Qy project.

Generated by 'django-admin startproject' using Django 1.11.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os
import sys

#import django.contrib.auth.middleware

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PARENT_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir))

sys.path.insert(0, BASE_DIR)
sys.path.insert(0, os.path.join(PARENT_DIR,'background'))
sys.path.insert(0, os.path.join(PARENT_DIR,'frontend'))
sys.path.insert(0, os.path.join(PARENT_DIR,'usermanage'))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'u8ctyimjuy7t-7r3%$&4sc2g^5fhc8dathp8z&(7pp=&eee@zn'

# SECURITY WARNING: don't run with debug turned on in production!
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',
    'django.contrib.sites',

    'corsheaders',

    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_docs', 
    'rest_auth',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'rest_auth.registration',

    ......
   
]

SITE_ID = 1


EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

#EMAIL_USE_TLS = True
EMAIL_USE_SSL = True
EMAIL_HOST = 'smtp.gmail.com'   # QQ:smtp.qq.com   163:smtp.163.com
EMAIL_PORT = 465
EMAIL_HOST_USER = 'qyserver@gmail.com'
EMAIL_HOST_PASSWORD = 'qiyunserver123'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER


REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES':[], #'rest_framework.permissions.IsAuthenticated'
    'DEFAULT_AUTHENTICATION_CLASSES':(
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ), #['rest_framework.authentication.TokenAuthentication'],  # 'rest_framework.authentication.TokenAuthentication'
    #'DEFAULT_PAGINATION_CLASS': ('rest_framework.pagination.PageNumberPagination',), 
    #'PAGE_SIZE':10,
}


REST_AUTH_SERIALIZERS = {
    'LOGIN_SERIALIZER': 'Qiyun02.common.Serializer.LoginSerializer',
    'TOKEN_SERIALIZER': 'Qiyun02.common.Serializer.TokenSerializer',
}


MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',

    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',

    'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',

    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    'Qiyun02.middlewares.AccessControlMiddleware.AccessControl',  # access-control

]

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

CORS_ORIGIN_ALLOW_ALL = False

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_WHITELIST = (
    'http://10.10.10.102',
    'http://10.10.10.102:8081',
    'http://10.10.10.102:8888',

    'http://10.10.10.103',
    'http://10.10.10.103:8000',
    'http://10.10.10.103:8080',
    'http://10.10.10.103:8081',
    'http://10.10.10.103:8888',

    'http://10.10.10.105:8000',
    'http://10.10.10.105:8001',
    'http://10.10.10.105:8080',
    'http://10.10.10.105:8888',

    'http://0.0.0.0:8000',
    'http://0.0.0.0:8001',
    'http://0.0.0.0:8080',
    'http://0.0.0.0:8888',

    'http://localhost:8081',
    'http://localhost',
    'http://localhost:8888',
)

######

ROOT_URLCONF = 'Qy.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# WSGI_APPLICATION = 'Qy.wsgi.application'

WSGI_APPLICATION = 'Qy.wsgi.django_app'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'qiyun02',
        'USER':'root',
        'PASSWORD':'devops',
        'HOST':'127.0.0.1',
        'PORT':'3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'zh-cn' # 'en-us'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/


STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR + '/static/'


STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

我的wsgi.py 代码如下:

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Qiyun02.settings")

# application = get_wsgi_application()

from socketio import Middleware
from xxx.xxx.qiyun_admin_website_chat.views import sio
django_app = get_wsgi_application()
application = Middleware(sio, django_app)

import eventlet
import eventlet.wsgi
eventlet.wsgi.server(eventlet.listen(('', 8000)), application)

当我访问此 URL 时: http://localhost:8000/api/users/list/

它不会加载静态文件:

但是如果我访问:http://localhost:8000/docs/

效果很好。

不知道为什么不加载样式文件。

谁能帮忙?


EDIT-1

当我跑步时:

python3 manage.py collectstatic

我得到以下错误:

STATICFILES_DIRS 设置不应包含 STATIC_ROOT 设置

追溯:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle
    collected = self.collect()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect
    for finder in get_finders():
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/staticfiles/finders.py", line 264, in get_finders
    yield get_finder(finder_path)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/staticfiles/finders.py", line 277, in get_finder
    return Finder()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/staticfiles/finders.py", line 66, in __init__
    "The STATICFILES_DIRS setting should "
django.core.exceptions.ImproperlyConfigured: The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting

【问题讨论】:

标签: python django django-rest-framework


【解决方案1】:

尝试运行python manage.py collectstatic

【讨论】:

  • 查看我的 EDIT-1,有问题。
【解决方案2】:

几年后,我遇到了同样的问题并找到了以下解决方案:

将以下行添加到您的“settings.py”文件中:

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-10
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多