Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

Some of my HTMLs are not loading CSS file

I have a main.css file where all my styles are and some of my html files are loading them, but not all of them. All my html files extends base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link href="static/css/main.css" rel="stylesheet" type="text/css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://kit.fontawesome.com/2a770f4891.js" crossorigin="anonymous"></script>

    <title>{% block title %}E-Learning{% endblock %}</title>
</head>
<body>

<input type="checkbox" id="check">
<nav class="nav">

        <label for="check">
            <i class="fas fa-bars" id="sidebar_btn"></i>
        </label>


        {% if user.is_authenticated %}
        {% if user.first_name != '' or user.last_name != '' %}
        <b class="top-menu" style="font-size:20px; margin-right:5px;"> Hello, {{user.first_name}} {{user.last_name}}</b>
        {% else %}
        <b class="top-menu" style="font-size:20px; margin-right:5px;">Hello, {{ user.username }}</b>
        {% endif %}
        {% else %}
        {% endif %}
            {% if user.is_authenticated %}
        <a href="{% url 'logout' %}" class="top-menu">Log out</a>
        {% else %}
        <a href="{% url 'login' %}" class="top-menu"> Log In </a>
        <a href="{% url 'register' %}" class="top-menu">Register </a>
        {% endif %}
    </nav>

    <div class="sidebar">
        <a href="{% url 'subject_new' %}" > <span> Add </span></a>
    </div>

    <main class="content">

        {% block content %}
        {% endblock content %}
    </main>

</body>
</html>

and for example my register.html extends base.html (with all css files) just fine

{% extends 'base.html' %}

{% block content %}

{% if user.is_authenticated %}

<b>You're already logged in.</b>

{% else %}

  <form method="post">
    {% csrf_token %}
     <div class="register-window">
    {% for field in form %}
       <p class="label_tag"> {{ field.label_tag }} </p>
       {{ field }}
        {% if field.help_text %}
          <br> <small class="help_text">{{ field.help_text }}</small>
        {% endif %}
        {% for error in field.errors %}
          <p style="color: red">{{ error }}</p>
        {% endfor %}
    {% endfor %}
    <button type="submit" class="login-button">Register</button>
     </div>
  </form>

{% endif %}

{% endblock %}

but my subject_detail.html seems to ignore my css file

{% extends 'base.html' %}



    {% block content %}
<head>

    <link rel="stylesheet" href="static/css/main.css" />
</head>
<body>
<div class="subjecttitle">{{subject.name}}</div>

<div class="subjectlessons"><p>{{subject.header|safe}}</p></div>
     {% endblock content %}
</body>

Also this html file doesn't load my css:

{% extends 'base.html' %}

{% block content %}

{% if user.is_teacher or user.username == 'admin' %}

<div class="card">
    <h2>Add subject</h2>
    <form method="POST" class="post-form" enctype="multipart/form-data">{% csrf_token %}
        {{ form.media }}
        {{ form.as_p }}
        {{ formfile.as_p }}
        <button type="submit" class="save btn btn-default">Save</button>
    </form>
    </div>
{% else %}
<b>You can't do this</b>
{% endif %}
{% endblock %}

I am doing this in django, so this is my settings.py

"""
Django settings for teamproject project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ewmxjw-q3eh=0-+9iq4*$8myvreo8-zg4v+*tkgz5q=+iqg%)q'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# ALLOWED_HOSTS = []
ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'eLearning',
    'ckeditor',
    'ckeditor_uploader',
    'crispy_forms',
    'django_cleanup',
]

CRISPY_TEMPLATE_PACK = 'bootstrap4'

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 = 'teamproject.urls'

TEMPLATE_PATH = os.path.join(BASE_DIR, 'eLearning/Templates')

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


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

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


# Password validation
# https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/

# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'pl-pl'

# TIME_ZONE = 'UTC'
TIME_ZONE = 'Europe/Warsaw'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

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

MEDIA_URL = '/media/'
MEDIA_ROOT = 'media/'

CKEDITOR_UPLOAD_PATH = "uploads/"

LOGIN_URL = '/login'
AUTH_USER_MODEL = 'eLearning.User'
LOGIN_REDIRECT_URL = 'home'

# gmail-mail settings
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_USER = "[email protected]"
EMAIL_HOST_PASSWORD = 'projektzespolowy1'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

CKEDITOR_CONFIGS = {
    'default': {
        "removePlugins": "resize, elementspath",
        'toolbar': 'Custom',
        'height': 300,
        'width': 600,        
        'toolbar_Custom': [
            ['Font', 'FontSize', 'Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', 'TextColor', 'BGColor', 'RemoveFormat', 'Blockquote', 'Smiley', 'SpecialChar'],
            ['Cut', 'Copy', 'Paste', 'SelectAll', 'Find', 'List', 'Preview', 'NumberedList', 'BulletedList', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', 'HorizontalRule'],
            [],
            ]
    }         
}

Every file extends base.html (I can tell by the header) but some of them ignore CSS file. If you need more files to try to solve my problem please ask and I will add this to question. Things I tried: I tried adding {% load static%}, python manage.py collectstatic, adding + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) at the end of my urls.py

EDIT: For subject_detail.html I tried to add CSS file in the most basic way:

{% block title %}E-Learning | Subjects{% endblock %}



    {% block content %}
<head>
    <link href="static/css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="subjecttitle">{{subject.name}}</div>
<div class="subjectlessons"><p>{{subject.header|safe}}</p></div>
     {% endblock content %}
</body>

even without extending base.html and adding

<link href="static/css/main.css" rel="stylesheet" type="text/css" />

but it still doesn't work. I don't know where problem is.

EDIT 2 This is my structure:

├───eLearning
│   ├───migrations
│   │   └───__pycache__
│   ├───static
│   │   ├───css (here is my main.css)
│   │   └───scripts
│   ├───Templates (here are all my .html files)
│   └───__pycache__

EDIT 3 This information that I get from cmd:

"GET /subject_detail/3/static/css/main.css HTTP/1.1" 404 5079 Not Found: /subject_detail/3/static/css/main.css


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have made some changes from your question and add like this in your code it should work. this is in your base.html file

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <link href="{% static 'css/main.css' %}" rel="stylesheet" type="text/css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://kit.fontawesome.com/2a770f4891.js" crossorigin="anonymous"></script>

    <title>{% block title %}E-Learning{% endblock %}</title>
</head>
<body>

<input type="checkbox" id="check">
<nav class="nav">

        <label for="check">
            <i class="fas fa-bars" id="sidebar_btn"></i>
        </label>


        {% if user.is_authenticated %}
        {% if user.first_name != '' or user.last_name != '' %}
        <b class="top-menu" style="font-size:20px; margin-right:5px;"> Hello, {{user.first_name}} {{user.last_name}}</b>
        {% else %}
        <b class="top-menu" style="font-size:20px; margin-right:5px;">Hello, {{ user.username }}</b>
        {% endif %}
        {% else %}
        {% endif %}
            {% if user.is_authenticated %}
        <a href="{% url 'logout' %}" class="top-menu">Log out</a>
        {% else %}
        <a href="{% url 'login' %}" class="top-menu"> Log In </a>
        <a href="{% url 'register' %}" class="top-menu">Register </a>
        {% endif %}
    </nav>

    <div class="sidebar">
        <a href="{% url 'subject_new' %}" > <span> Add </span></a>
    </div>

    <main class="content">

        {% block content %}
        {% endblock content %}
    </main>

</body>
</html>

and this is in your subject_detail.html file

{% block content %}
<div class="subjecttitle">{{subject.name}}</div>

<div class="subjectlessons"><p>{{subject.header|safe}}</p></div>
     {% endblock content %}

if it is working on your base.html than by doing this it should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...