My css file is not getting loaded in the webpage. I have css and image file in the same location. The image is getting loaded but not the css.Also I have included the directory in staticfile_dirs.
Setting.py
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'technicalCourse.apps.TechnicalcourseConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'website.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
r'C:\Users\Kesavan\PycharmProjects\Django web development\website\technicalCourse\template'
],
'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 = 'website.wsgi.application'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
r'website\technicalCourse\static',
]
This the template file
<!DOCTYPE html>
{% load static %}
<head>
<link rel="stylesheet" type="text/css" href="{% static 'css/simple.css' %}">
</head>
<body>
<img src="{% static 'image/img.png' %}">
<h1>Welcome to course on programming</h1>
<ol>
{% for x in ac %}
<li>{{x.courseName}}</li>
{% endfor %}
</ol>
</body>
For testing I simply change the color of the h1 tag alone. The css file.
h1{
color:black;
}
Structure
C:.
├───migrations
│ └───__pycache__
├───static
│ ├───css
│ └───image
├───template
│ └───technicalCourse
└───__pycache__
But there is no reflection on the webpage.
Hoping for the solution.
Thanks in advance.
try this command:
python manage.py collectstatic
and check again.
It's weird that images are working and CSS isn't. There could be a multitude of possibilities for your problem.
The simplest way to solve this is to set the path to the CSS files via an absolute or a relative path.
Relavtive path case
<link href="/static/ui/css/base.css" rel="stylesheet">
I was suffering with same problem but solved by adding the
{% load static %}
{
<link rel="stylesheet" type="text/css" href="{% static 'thumbnail_searcher/style.css' %}">
}
in same tag. For example in your case add load and link into <head> tag.
clear browser cache
in settings.py change STATIC_URL = "static/" to STATIC_URL = "/static/"
run python manage.py runserver port_number(optional)
Try
$ python manage.py findstatic css/style.css
instead of css/style.css add your own path
If Django project able to locate the CSS, it will return path to your CSS file.
Then restart your project and it should work.
Related
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). I can't get my css static file to load on this practice page, css_practice.html.
I have the following structure
djangoAjax
settings.py
...
djangoAjaxApp
static
ok.css
templates
css_practice.html
My settings.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:
<!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:
# css practice
def cssRender(request):
return render(request, "css_practice.html")
urls.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/
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.
Currently the page loads, but css is not applied.
Thanks for your help
settting.py:
STATIC_URL = '/static/'
Only one {% load static %} is enough in your html code:
<!DOCTYPE html>
{% load static %}
You have to Copy and Plast your STATIC files (Js, CSS, ...) in your templates.
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:
<link type="text/css" rel="stylesheet" href"{% static 'djangoAjaxApp\ok.css' %}">
views.py:
# css practice
def cssRender(request):
return render(request, "djangoAjaxApp/css_practice.html")
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.cssRender, name='cssRender'),
]
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 ...
]
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).
I've formatted my base page properly and I have used the correct tags in my HTML pages, yet my local css file (main.css) will not load.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
{% block head %}
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load static %}
<link rel="stylesheet" type="text/css" media="screen" href="{% static 'css/main.css' %}"/>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght#300&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
{% block script %}
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/07a07b3c8d.js" crossorigin="anonymous"></script>
{% endblock %}
<title>{% block title %}Edward's Portfolio{% endblock %}</title>
<style>
body {
font-family: "Source Code Pro", monospace;
}
</style>
{% endblock %}
</head>
<body>
{% block content %}
<h1>My Portfolio</h1>
{% endblock %}
</body>
</html>
Settings.py:
from pathlib import Path
import os.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.2/howto/deployment/checklist/
# 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',
'PortfolioApp'
]
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 = 'Portfolio.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',
'django.template.context_processors.media'
],
},
},
]
WSGI_APPLICATION = 'Portfolio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/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.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/'
STATIC_ROOT = [os.path.join(BASE_DIR, 'static')]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media/')
MEDIA_URL= "/media/"
Here is the structure of my static folder:
I have set my STATIC_ROOT and STATIC_URL correctly in settings.py but I have still found no success. If I could get some assistance I would appreciate it.
If your trying to do this with DEBUG=True you also need to set STATICFILES_DIR
https://docs.djangoproject.com/en/3.2/howto/static-files/#configuring-static-files
If you can post your settings.py with ALL of these set wecan help.
STATIC_ROOT is used in production, with DEBUG to False and you run
python manage.py collectstatic. So if your in production and having this issue you first need to set the urls for django to serve static files
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
then run the command python manage.py collectstatic
A quick example for specifying static directory in production/dev (DEBUG=True/False)
STATIC_URL = '/static/'
if DEBUG:
STATICFILES_DIRS = BASE_DIR / 'static' # this is a top-level static directory (same level as manage.py), you can create a list of dirs if you have static files in each app. This value is checked DEBUG=True
else:
STATIC_ROOT = BASE_DIR / 'static' # this value is checked in production
Update your static settings like this:
STATIC_URL = '/static/'
STATIC_ROOT = f'{BASE_DIR}{STATIC_URL}'
STATICFILES_URL = '/staticfiles/'
STATICFILES_DIRS = [f'{BASE_DIR}{STATICFILES_URL}',]
And inside urls.py, write this:
from django.conf import settings
from django.conf.urls.static import static
# After urlpatterns
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Then rename your static folder to staticfiles
It seems that my static file doesn't work properly in my django project. I'm not sure whether this is exactly related to js files or the whole static file. Checking related questions, I couldn't find how to solve this problem. So, I send what my template should look like and how it looks in my browser in the below screenshots:
what my template should look:(when scrolling down, the background image also moves)
But this is how my browser shows the template: (no background images, no padding adjustments)
This is my base.html codes:
{% 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">
<!-- Font Awesome -->
<link rel="stylesheet" href="{% static 'css/all.css' %}">
<!-- Bootstrap -->
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
<!-- Custom -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<!-- LightBox -->
<link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}">
<title>BT Real Estate</title>
</head>
<body>
<!-- Top Bar -->
{% include 'partials/_topbar.html' %}
<!-- Navbar -->
{% include 'partials/_navbar.html' %}
<!--- Main Content -->
{% block content %} {% endblock %}
<!-- Footer -->
{% include 'partials/_footer.html' %}
<script src="{% static 'js/jquery-3.3.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.bundle.min.js' %} "></script>
<script src="{% static 'js/lightbox.min.js' %} "></script>
<script src="{% static 'js/main.js' %} "></script>
</body>
</html>
Also, this is how I addressed my static file in settings.py:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'listings.apps.ListingsConfig',
'realtors.apps.RealtorsConfig',
'pages.apps.PagesConfig',
'django.contrib.auth',
'django.contrib.humanize',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'btre.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 = 'btre.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': '******',
'USER': '******',
'PASSWORD': '******',
'HOST': 'localhost',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/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.0/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.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'btre/static')
]
# Media Folder Settings
MEDIA_ROOT = os.path.join (BASE_DIR, 'media')
MEDIA_URL ='/media/'
Here is my urls.py codes:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('pages.urls')),
path('listings/', include('listings.urls')),
path('admin/', admin.site.urls),
] + static (settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Here is how I extend base.html in index.html: (I just brought the show case's codes here)
{% extends 'base.html' %}
{% load humanize %}
{% block content %}
<!-- Showcase -->
<section id="showcase">
<div class="container text-center">
<div class="home-search p-5">
<div class="overlay p-5">
<h1 class="display-4 mb-4">
Property Searching Just Got So Easy
</h1>
<p class="lead">Lorem ipsum dolor sit, amet consectetur adipisicing elit.Recusandae quad,
asperiores eveniet vel nostrum magnam
voluptatum tempore! Consectetur, id commodi!</p>
<div class="search">
<form action="search.html">
<!-- Form Row 1 -->
#pass
{% endblock %}
And finally, here is the hierarchy of my static file:
Why did such a problem happen? Can somebody help me out with this problem?
Thank you.
I think you have to include in your settings a media root and a media url. I use the following settings.
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [os.path.join(BASE_DIR),'static']
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')
Also then in your URLS, make sure you have the following settings:
(first import static and settings), then enter the following code at the end!
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I think this might fix the problem if the images that aren't displaying are on your local machine.
Just remove the "/cover" and put just "fixed" instead of "fixed/cover" from the "main_app/static/css/style.css/showcase"
I need to incorporate css in my templates to help them look better, but inspite of adding the static url and root, I am just not able to load it in my template. I am attaching the relevant code here. Please tell me what am I doing wrong. Thanks in advance.
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATIC_ROOT = [STATIC_DIR,],
index.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<link href="{% static 'css/index.css' %}">
</head>
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'project_name/static')
]
index.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<link href="{% static 'css/index.css' %}" rel="stylesheet">
</head>
for more information check here
for loading static files you need to add the static url too
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
......
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
add these in your project's root url
Change url base urls.py like following
urlpatterns = [
# your url here
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Also include {% load static %} tag in your template
There is no settings named STATIC_DIR, it should be STATICFILES_DIRS and should be declared like this:
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR,'staticroot') # Static Dir and Static root needs to be different
As for serving static files, as per documentation, if you add django.contrib.staticfiles in INSTALLED_APPS, then django will serve static automatically when DEBUG is True. But in production, you need to use a reverse proxy server to static files. Or you can use whitenoise. More information can be found in documentation as well.
Which version of Django do you using? Starting from 2.0 there are some changes, instead of
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
there is
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',
],
},
},]
Also check out is your static folder even exist
And be sure that you have chosen right path to your static folder(for example I hold this folder inside of template folder so my code looks like this)
STATIC_URL = '/templates/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "templates/static"),]
And I see that you didn't put csrf_token to your html, so please add this to your html
{% csrf_token %}
I am currently making a Web App using the Django framework and have just started recently. I looked through the Django Documentation and also looked through many tutorials and other answers on StackOverflow but none of them seem to work. When I first placed the link on the HTML page I included the {% static 'my_app/css/cssFile'%}and also included {% load staticfiles %}. I have also tried including this into my settings file: STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static'])) but none of these work. Every time I try to run the server, the console keeps saying that the server could not find the resource and that it exited out as a 404.
This is my settings file:
"""
Django settings for WebApp project.
Generated by 'django-admin startproject' using Django 2.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
import posixpath
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
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/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6-_^kvfdcg&#+_gdf1ub*ood*$fm4vs1m-aw_uw#(2tliu9(d0'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'WebApp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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 = 'WebApp.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 = 'WebApp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/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/2.0/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/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = posixpath.join(*(BASE_DIR.split(os.path.sep) + ['static']))
My very simple HTML file that I am using for testing:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }} - My Django Application</title>
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'WebApp/css/layout.css' %}">
</head>
<body>
<div class="navbar clearfix">
<div class="container">
<div class="logo"></div>
<div class="menu-item">
<ul class="item-list">
Home
About
Question
</ul>
</div>
</div>
</div>
<div class="content">
<div class="container-content">
{% block content %}{% endblock %}
</div>
</div>
{% block scripts %}{% endblock %}
</body>
</html>
And the CSS file that I made:
div.navbar {
width: 100%;
color: #FFF;
height: 10px;
background-color: #000000;
}
.clearfix {
content: "";
clear: both;
display: table;
}
.container {
background-color: #000;
width: 100%;
height: 100%;
}
I have set up my directories as follows:
Any help would be greatly appreciated.
Check this im using this now and works.
Settings
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,"media")
and i call in this way
<link href="{% static 'app/vendor/bootstrap/css/bootstrap.min.css'%}" rel="stylesheet">
in urls
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change the next template tag:
{% load staticfiles %}
for:
{% load static %}