简体   繁体   English

Django static css 未加载到页面上

[英]Django static css is not loading on page

I know there are many posts about this, but I have been unable to resolve my problem (for example following this: Django static files (css) not working ).我知道有很多关于此的帖子,但我一直无法解决我的问题(例如以下: Django static files (css) not working )。 I can't get my css static file to load on this practice page, css_practice.html.我无法在此练习页面 css_practice.html 上加载我的 css static 文件。

I have the following structure我有以下结构

djangoAjax
 settings.py
 ...
 djangoAjaxApp
   static
     ok.css
   templates
     css_practice.html

My settings.py:我的设置.py:

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = '############################################'

# 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',
    "crispy_forms",
    'djangoAjaxApp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    '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 = 'djangoAjax.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 = 'djangoAjax.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


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/3.2/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/3.2/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'), BASE_DIR / "static",
]

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

my html page:我的 html 页面:

<!DOCTYPE html>
{% load static %}
<html>
<head>
{% comment %} https://www.bing.com/videos/search?q=django+static+css&docid=608004894969656896&mid=E118E7C4ADFE161B3B12E118E7C4ADFE161B3B12&view=detail&FORM=VIRE {% endcomment %}
    {% load static %}
    <link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\static\ok.css' %}">
<title>Page Title</title>
</head>
<body>

<h1 class="ok">My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>

views.py:视图.py:

# css practice
def cssRender(request):
     return render(request, "css_practice.html")

urls.py:网址.py:

from django.urls import path
from .views import cssRender

urlpatterns = [
    path('css/', cssRender, name='cssRender'),
]

I imagine I might be messing up the folder structure somehow... there is also a reference in the django docs: https://docs.djangoproject.com/en/3.2/howto/static-files/我想我可能会以某种方式弄乱文件夹结构...... django 文档中还有一个参考: https://docs.djangoproject.com/en/3.2/howto/static-files/

about adding关于添加

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

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

But since I am using, django.contrib.staticfiles in settings, I'm assuming this is done automatically.但由于我在设置中使用django.contrib.staticfiles ,我假设这是自动完成的。

Currently the page loads, but css is not applied.当前页面加载,但未应用 css。

Thanks for your help谢谢你的帮助

Could you please try it.你能试试吗。

from django.contrib.staticfiles.urls import staticfiles_urlpatterns


if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()

Just to remind you of it, have you tried hard refresh on your browser?提醒您一下,您是否尝试过在浏览器上努力刷新? I used to miss this when I was a beginner.当我还是初学者时,我曾经错过这个。 (You can do it in chrome with ctrl+shift+r). (您可以使用 ctrl+shift+r 在 chrome 中执行此操作)。

settting.py: STATIC_URL = '/static/' settting.py: STATIC_URL = '/static/'

Only one {% load static %} is enough in your html code:您的 html 代码中只有一个{% load static %}就足够了:

 <!DOCTYPE html> {% load static %}

You have to Copy and Plast your STATIC files (Js, CSS, ...) in each App with templates(html) that you created.您必须使用您创建的模板(html)在每个应用程序中复制并粘贴您的 STATIC 文件(Js、CSS、...)。 It will look like that:它看起来像这样:

 djangoAjaxApp |_migrations |_templates | |_djangoAjaxApp | |_css_practice.html |_static |___djangoAjaxApp (directory with the same App name) |_(here all your static file)

Your HTML will look like this:您的 HTML 将如下所示:

 <link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\ok.css' %}">

views.py:视图.py:

# css practice

def cssRender(request):

    return render(request, "djangoAjaxApp/css_practice.html")

urls.py:网址.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.cssRender, name='cssRender'),
        ]

djangoAjax urls.py: djangoAjax urls.py:

from django.conf import settings
from django.contrib import admin
from django.urls import path

urlpatterns = [
    # ... the rest of your URLconf goes here ...
    ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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