简体   繁体   中英

css not loading in my login and admin page in django

I'm newbie in django and I started learning django with official tutorial.

I use django beside virtualenv, but I have a problem with the login page and admin page because

they aren't load css and show login page and admin page without any style

"""
Django settings for mysite project.

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

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

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

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g8%o@ackd!hzekoho4rn7r7-t_m!sk$*nwi-4j556t=!ln3(@+'

# 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',
    'polls',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'mysite.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Internationalization
# https://docs.djangoproject.com/en/1.8/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.8/howto/static-files/

STATIC_URL = '/static/'

First of all, Create folder named as "static", then you need to copy all the css/js file into static folder inside your project(or wherever you create static folder). Then declare the static files directory path in your settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = ('assets', BASE_DIR +'/static/',)

In your html file, add following line -
{% load staticfiles %}
at top of the header section or top of the file.
In <head> section you can link the css/js file using following code

<link rel="stylesheet" href="{% static 'assets/css/mystyle.css'%}">
</link>
<script src="{% static 'assets/js/jquery.js'%}"></script>

You need to read through the documentation for serving static files . When you are in production, your webserver (nginx/apache) would be responsible for serving static files such as JS, CSS and images. So any request for an image or JS file would be taken care of immediately by the webserver while any request for an actual page would be passed to your application server (ie Django)

In development you need to tell the development server to actually serve your static files so you need to add the following to your root urls.py file:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

There are two situations that you maybe fail to load CSS files.

  1. login Interceptor catch all the request, including your static files
  2. browser cannot access your CSS files.

It is easy to judge what situation you are in. You can open your browser and check whether your CSS request is received. (for example, open your Chrome by F12 and check Console ).

If there is not an error about failing to receive. Maybe your login Interceptor has caught all the things. And then, you can dig into what you received, at that you will find the answer. on my case, I find the response is my login page, not my ccs file.

You should let them go like this.

if static('') in request.path:
    return self.get_response(request)

If received, you can see other answers.

(My English is not very good. If you want, you can edit this answer.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM