2

I use Django-Rest-Framework, but get bellow error when I open the DRF APIs:

The styles and Scripts can not load:

GET http://localhost:8000/static/rest_framework/css/bootstrap.min.css net::ERR_ABORTED
localhost/:20 GET http://localhost:8000/static/rest_framework/css/bootstrap-tweaks.css net::ERR_ABORTED
localhost/:23 GET http://localhost:8000/static/rest_framework/css/prettify.css net::ERR_ABORTED
localhost/:24 GET http://localhost:8000/static/rest_framework/css/default.css net::ERR_ABORTED
(index):219 GET http://localhost:8000/static/rest_framework/js/ajax-form.js net::ERR_ABORTED
(index):218 GET http://localhost:8000/static/rest_framework/js/jquery-1.12.4.min.js net::ERR_ABORTED
(index):220 GET http://localhost:8000/static/rest_framework/js/csrf.js net::ERR_ABORTED
(index):221 GET http://localhost:8000/static/rest_framework/js/bootstrap.min.js net::ERR_ABORTED
(index):222 GET http://localhost:8000/static/rest_framework/js/prettify-min.js net::ERR_ABORTED
(index):223 GET http://localhost:8000/static/rest_framework/js/default.js net::ERR_ABORTED
(index):219 GET http://localhost:8000/static/rest_framework/js/ajax-form.js 404 (Not Found)
(index):220 GET http://localhost:8000/static/rest_framework/js/csrf.js net::ERR_ABORTED
(index):221 GET http://localhost:8000/static/rest_framework/js/bootstrap.min.js net::ERR_ABORTED
(index):222 GET http://localhost:8000/static/rest_framework/js/prettify-min.js net::ERR_ABORTED
(index):223 GET http://localhost:8000/static/rest_framework/js/default.js net::ERR_ABORTED

enter image description here

and the Network:

enter image description here


but the docs is ok, the Style and Script all work fine:

enter image description here


EDIT -1

My Python version is Python 3.5.2

I use pip list:

My Django version: 1.11.1

Django (1.11.1)
django-rest-auth (0.9.2)
djangorestframework (3.7.1)

EDIT-2

In my wsgi.py, I use eventlet, I don't know whether this affect:

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

#application = get_wsgi_application()

from socketio import Middleware
from xxx.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)

EDIT-3

This is the my settings.py:

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

"""
Django settings for Qiyun02 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目录
sys.path.insert(0, BASE_DIR)
sys.path.insert(0, os.path.join(PARENT_DIR,'旗云管理员后台'))
sys.path.insert(0, os.path.join(PARENT_DIR,'用户前台'))
sys.path.insert(0, os.path.join(PARENT_DIR,'用户管理后台'))


# 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',  # API文档
    'rest_auth',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'rest_auth.registration',


    # apps
    ...... 

]

SITE_ID = 1


# email backend TODO  
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 = 'qiyunserver@gmail.com'
EMAIL_HOST_PASSWORD = 'qiyunserver123'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER


# TODO 方便调试,关闭Token验证
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中间件

]

# TODO: 发布时候去掉
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

# TODO: 发布时候去掉
CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)
# TODO: 发布时候去掉
CORS_ORIGIN_ALLOW_ALL = False

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_WHITELIST = (

    'http://10.10.10.102:8081',
    'http://10.10.10.103:8000',
    'http://10.10.10.103:8080',
    'http://10.10.10.105:8000',
    'http://10.10.10.105:8001',
    'http://10.10.10.105:8080',

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

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

######

ROOT_URLCONF = 'Qiyun02.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 = 'Qiyun02.wsgi.application'


# 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/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

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

I tried change the WSGI_APPLICATION = 'Qiyun02.wsgi.django_app', but still do not work for me.


EDIT-4

I add the STATIC_ROOT=BASE_DIR + '/static/', but still not work.

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

EDIT-5

After I change the wsgi.py to the previous:

import os

from django.core.wsgi import get_wsgi_application

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

application = get_wsgi_application()

It works fine now.

So, the issue is in the wsgi.py.

See the upper EDIT, I tried change the WSGI_APPLICATION = 'Qiyun02.wsgi.django_app' in the settings.py, but still do not work for me.


EDIT-6

WHY? IT DO NOT WORK NOW.

the traceback are:

Not Found: /static/rest_framework/js/prettify-min.js
127.0.0.1 - - [13/Mar/2018 18:49:15] "GET /static/rest_framework/js/prettify-min.js HTTP/1.1" 404 5713 0.020659
Not Found: /static/rest_framework/js/jquery-1.12.4.min.js
127.0.0.1 - - [13/Mar/2018 18:49:15] "GET /static/rest_framework/js/jquery-1.12.4.min.js HTTP/1.1" 404 5728 0.043330
Not Found: /static/rest_framework/js/ajax-form.js
127.0.0.1 - - [13/Mar/2018 18:49:15] "GET /static/rest_framework/js/ajax-form.js HTTP/1.1" 404 5704 0.021123
Not Found: /static/rest_framework/js/default.js
127.0.0.1 - - [13/Mar/2018 18:49:15] "GET /static/rest_framework/js/default.js HTTP/1.1" 404 5698 0.020581
Not Found: /static/rest_framework/js/csrf.js
127.0.0.1 - - [13/Mar/2018 18:49:16] "GET /static/rest_framework/js/csrf.js HTTP/1.1" 404 5689 0.020562
Not Found: /static/rest_framework/js/bootstrap.min.js
127.0.0.1 - - [13/Mar/2018 18:49:16] "GET /static/rest_framework/js/bootstrap.min.js HTTP/1.1" 404 5716 0.021161
Not Found: /static/rest_framework/js/prettify-min.js
127.0.0.1 - - [13/Mar/2018 18:49:16] "GET /static/rest_framework/js/prettify-min.js HTTP/1.1" 404 5713 0.019709
Not Found: /static/rest_framework/js/default.js
127.0.0.1 - - [13/Mar/2018 18:49:16] "GET /static/rest_framework/js/default.js HTTP/1.1" 404 5698 0.023551

My configure is :

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

"""
Django settings for Qiyun02 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目录
sys.path.insert(0, BASE_DIR)
sys.path.insert(0, os.path.join(PARENT_DIR,'旗云管理员后台'))
sys.path.insert(0, os.path.join(PARENT_DIR,'用户前台'))
sys.path.insert(0, os.path.join(PARENT_DIR,'用户管理后台'))


# 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', # 跨域头  TODO: 发布时候去掉 (不能去掉,要保证两个站点访问一个APIs)

    'rest_framework',
    'rest_framework.authtoken',
    'rest_framework_docs',  # API文档
    'rest_auth',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'rest_auth.registration',

    ......

]

SITE_ID = 1


# email backend TODO 这个,每个商户可以自己定义邮箱
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 = 'qiyunserver@gmail.com'
EMAIL_HOST_PASSWORD = 'qiyunserver123'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER


# TODO 方便调试,关闭Token验证
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',   # TODO: 发布时候去掉
    '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中间件

]

# TODO: 发布时候去掉
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

# TODO: 发布时候去掉
CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept-encoding',
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)
# TODO: 发布时候去掉
CORS_ORIGIN_ALLOW_ALL = False

CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_WHITELIST = (
    'http://10.10.10.102',
    'http://10.10.10.102:8000', # 官网
    'http://10.10.10.102:8080', # 管理员后台
    '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 = 'Qiyun02.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 = 'Qiyun02.wsgi.application'

WSGI_APPLICATION = 'Qiyun02.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')
aircraft
  • 25,146
  • 28
  • 91
  • 166

4 Answers4

1

Are you sure that your static files are on the location as /static/ because what I see in the command terminal is /static/rest_framework/

I guess try making your STATIC_URL = '/static/' to STATIC_URL = '/static/rest_framework/'

This will help.

1

Run this command to generate static files for the DRF:

python manage.py collectstatic
AS Mackay
  • 2,831
  • 9
  • 19
  • 25
Vishal Pandey
  • 11
  • 1
  • 4
0

Try a fresh install. Make sure you are using this in a custom virtual environment. do the following:

mkdir projects cd projects mkdir test_app (name of a app folder-call it anything you want) cd test_app

start your virtual environment

and install django...pip install django==2.0

start your django project

django-admin startproject test_app . (don't forget the dot)

in your top level folder with manage.py in it, do the following:

django-admin startapp myapp # where myapp is the name of your app

this will create additional folder and new files

cd into your settings.py and add myapp in your installed app section on top of the list

go back to your top level folder with manage.py in it and type

python manage.py migrate

python manage.py runserver

Community
  • 1
  • 1
turtle_in_mind
  • 986
  • 1
  • 18
  • 36
0

Thanks for @AnupYadav

Now I change the

WSGI_APPLICATION = 'Qiyun02.wsgi.django_app'

in my settings.py,

and add the STATIC_ROOT = BASE_DIR + '/static/' in my settings.py:

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

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

It works for me.


EDIT-1

Now, the method do not work any more, I don't know why. Before is good, I did nothing why it do not work now?

aircraft
  • 25,146
  • 28
  • 91
  • 166