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
Related
so i am working on a project where i want to use some css files. but i couldn't link them with my html page in django. i've used everything i knew but still static is not loading
my error is:
(staticfiles.W004) The directory 'C:\Users\ASUS\PycharmProjects\e-payment\epayment\static' in the STATICFILES_DIRS setting does not exist.
my code snippets are given below:
my setting is:
settings.py
Django settings for epayment project.
Generated by 'django-admin startproject' using Django 4.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
import os
# 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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-+)&^ze^f+g#k28j#(1&r8y#u)g4=9!g7c4ef-i07!5#yhq2dd3'
# 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',
'epayapp',
]
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 = 'epayment.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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 = 'epayment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
here'e my base file that i am using
base.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title%} {% endblock %}</title>
<link rel="stylesheet" href="{% static '/epayapp/main.css'%}" type="text/css">
{% load static%}
<link rel="stylesheet" href="/static/common-styles.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
</head>
<style>
nav {
background-color: orange;
}
h2 {
font-family: "PT Serif";
}
h4 {
font-weight: 900;
}
#curr_bal {
border: 4px solid;
border-radius: 100px;
}
.current {
border: 1px solid;
padding: 3px;
}
.curr_bal {
font-family: "Cinzel";
font-weight: 600;
}
.col-sm-3
{
display: inline-block;
margin-left: -4px;
{% block css %} {% endblock %}
</style>
<body>
{% block body %}
{% endblock %}
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a+RTT6rIHI7NnikvbZlHgTPOOmMi466C8" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.1/dist/js/bootstrap.min.js" integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous"></script>
{% block script %} {% endblock %}
</body>
</html>
my css file that i want to link with
main.css
body {
background-color: floralwhite;
}
thanks in advance
you need to simply create a folder with a name with which the error has caused, In simple words you need to create a folder named by static in your following path which is also shown in error itslef "(staticfiles.W004) The directory 'C:\Users\ASUS\PycharmProjects\e-payment\epayment\static' in the STATICFILES_DIRS setting does not exist.", the static folder is missing therefore the problem was invoked, i also had the same error "?: (staticfiles.W004) The directory '/home/mrnecro/dj_social/bffbook/static_project' in the STATICFILES_DIRS setting does not exist." so subsequently i did the same, i just created the the folder named by static_project and restarted the server again and the problem was gone!
Thankyou, hope this may help you, do comment if its not.
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).
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 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 %}
My index.html won't connect to my index.css for some reason. I can't see why. Maybe it's the path of files or something. I apologize for such a noob question. My index.css file has a small bit of code just to test out and see if it works.
Here's my index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Page</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
{% load static %}
<link rel="stylesheet" href="{% static 'index.css' %}">
</head>
<body>
<div class="container">
<form method="POST">
{% csrf_token %}
<div class="form-group">
<label for="firstName">First Name:</label>
<input class="form-control" id="firstName" placeholder="Enter first name" name="firstName">
</div>
<div class="form-group">
<label for="">Last Name:</label>
<input class="form-control" id="lastName" placeholder="Enter last name" name="lastName">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember">Remember me</label></div></br>
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</body>
</html>
Here's my index.css file:
html {
background: chocolate;
}
Here's 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__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+-9mn+q&u#lw2_=s7&=zin5d7oxbt#v#9jg%2+a7=#noqd_jyf'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'music.apps.MusicConfig',
'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 = 'tyran.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 = 'tyran.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/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/1.11/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/1.11/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.11/howto/static-files/
STATIC_URL = '/static/'
You should load the static files with correct way in Django, better to split static files and templates. Here is one solution based on your case:
Fristly, under music folder, create static folder, put your static file index.css.
After that, change the loading css file with this way in your index.html:
{% load static%}
<link rel="stylesheet" href="{% static 'index.css' %}">
Then, it will load the static file.
Update:
make sure index.css is in the path: tyran/music/static/index.css
Just give it a hard path instead:
<link rel="stylesheet" href="~/music/templates/music/index.css">
Django is looking for a file called "index.css" relative to your project root, not the template directory. See this documentation (https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-static-files-during-development) about setting up a STATIC_URL directory to tell Django where to look for static assets.
There's nothing wrong in the code.
I copied your code and ran on my machine. It works fine.
There's no problem in your code. The connection also is too correct. Try doing it in other IDE or manually.