-1

i inserted a css file to my django project (in 'static' directory) and set address of this css to my index.html file (in 'template' directory) according to django dacumentation but my css dosn't work!

this is my addresses:

myproject/myapp/templates/html/index.html

myproject/myapp/static/css/index.css

this is my html:

{% load static %}

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head lang="eng">
<link rel="stylesheet" type="text/css" href={% static "css/index.css" %}/>
</head>

<body onload="myFunction()">
----some code----
</body>
</html>

this is my settings.py file:

import os

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '83lia*q_t0q%=hm==3#s*h$=s5(4!l44s698r326zgpz*v4csl'

# 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',
    'myapp',
]

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

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
        '././myapp/templates/html',

        ],
        '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 = 'myproject.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(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',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

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

this is my urls.py:

from django.contrib import admin
from django.urls import path , include
admin.autodiscover()

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.url')),
]

this is url.py file in myapp directory:

from django.urls import path , include
from . import views

urlpatterns = [
    path('', views.index, name = 'index'),

]

and this is my veiws.py fie:

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
 return render(request, 'index.html',{})

but my css dosn't work!i get 404 error! please help me to run myproject completely

mahsa.p.b
  • 39
  • 4
  • Can you post your whole `settings.py`, your `urls.py` and also it'd be nice if you describe what's happening. Are you seeing any errors? – Higor Rossato Jun 26 '19 at 14:07
  • @HigorRossato i edited my question and posted other files, my html file coming up but without css and i get 404 error in windows cmd ! thanks for your attention :) – mahsa.p.b Jun 27 '19 at 09:39

3 Answers3

0

Try using:

{% static "css/index.css" %}

in

<link rel="stylesheet" type="text/css" href={% static "myapp/index.css" %}/>
  • oh you're right! i changed it but my css dosn't work yet ! i get 404 error about my css address in cmd – mahsa.p.b Jun 27 '19 at 08:40
  • So a 404 error just means that the file can't be found, You could try deleting: `STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'myapp/static') ]` and see if that resolves the 404 error. – Erick Y. Carreno Jun 27 '19 at 15:43
  • i do that but the result don't change! i get 404 error again – mahsa.p.b Jun 28 '19 at 13:16
0

let's try

first at all create a folder at root dir called static then create another folder inside call css then put yours files.

in settings.py you should have. remove static_root and put STATICFILES_DIRS

STATIC_URL = '/static/'

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

in you html file put

<link rel="stylesheet" type="text/css" href={% static "css/index.css" %}/>

it should works.

if you want to know morea bout the difference between static_root and staticfiles_dirs please check out this answer for anothe user. statict_root vs staticfiles_dis

Bob White
  • 733
  • 5
  • 20
0

The only thing I don't see on the answers and in your trials is the code to serve the static files during development on your urls.py. Although it might not fix your issue, it's worth trying. You can read more about it here

global urls.py

from django.conf import settings
from django.contrib import admin
from django.urls import path , include
from django.conf.urls.static import static
admin.autodiscover()

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.url')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Higor Rossato
  • 1,996
  • 1
  • 10
  • 15
  • it dosn't work again! i get this error: NameError: name 'static' is not defined – mahsa.p.b Jun 27 '19 at 10:31
  • also i read that link and try all of tips but i have no result! do you know what?! even my images come up with my html but my css no!! i think it's weird! – mahsa.p.b Jun 27 '19 at 10:36
  • You’re probably getting errors on your browser console. It’d be nice if you post them – Higor Rossato Jun 27 '19 at 10:39
  • Try to print your `BASE_DIR` inside your `settings.py` just to check if that's the correct path your using. Also, another thing is your `ALLOWED_HOST`. It should be, whilst in development mode of course, `ALLOWED_HOST = ['*']` – Higor Rossato Jun 27 '19 at 11:26
  • i change ```ALLOWED_HOST``` value but the result dosn't change! how i can print ```BASE_DIR``` inside settings.py ? – mahsa.p.b Jun 28 '19 at 13:33