I am new to Django. I am developing a dynamic website which include CSS in it.
I am using template inheritance.When I try to include CSS files I am getting a "404 Page not Found" error for CSS file. Please help me.
Here's my project structure:
Here's my urls.py file:
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^courses/', include('courses.urls')),
url(r'^admin/', admin.site.urls),
url(r'^$', views.hello_world),
]
urlpatterns += staticfiles_urlpatterns()
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.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '5%#*z=7o5iap!lnr7(%*(2rsl#*b-ufjy!ia$8z08d(6d8!j-#'
# 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',
'courses',
]
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 = 'learning_site.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 = 'learning_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/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.10/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.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
STATIC_FILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Here's my layout.html file:
{% load static from staticfiles %}
<html>
<head>
<title>
{% block title %}{% endblock title %}
</title>
<link rel='stylesheet' href="{% static 'css/layout.css' %}">
</head>
<body>
{% block content %}print something for fun...{% endblock content %}
</body>
</html>
Here's my home.html file:
{% extends 'layout.html' %}
{% block title %}Hello World {% endblock title%}
{% block eontent %}
<h1>
welcome!!!
</h1>
{% endblock content %}
If you are using Django 1.10
here is the documentation of STATICFILES_DIRS
change your
STATIC_FILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
to
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
'static',
]
And in your base html change the {% load static from staticfiles %} to {% load static %}
STATIC_FILES_DIRS is no django settings config name use STATICFILES_DIRS instead.
If your static folder is inside you base project app .
Something like.
django_project (your manage.py is here) -> django_project -> static
then your static file config should be like.
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'django_project/static'),
)
You shouldn't need any changes in your urls for this.
Update: The above doesn't seem to be true.
Your template syntax for block tag is incorrect.
Can you please fix that and check . You don't endblock and blockname
<html>
<head>
<title>
{% block title %}{% endblock %}
</title>
<link rel='stylesheet' href="{% static 'css/layout.css' %}">
</head>
<body>
{% block content %}print something for fun...{% endblock %}
</body>
</html>
Update 2:
Also template context process needs to be like this.
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.core.context_processors.static",
'django.contrib.messages.context_processors.messages',
],
},
},
]
Related
My static files are not loading on Django. I'm running this on my local machine. The location of example.png is main/static/main/example.png. main is an app.
Here's my settings.py:
from pathlib import Path
import os
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'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 = 'tutorials.urls'
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR, ],
'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 = 'tutorials.wsgi.application'
...
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
My template, index.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<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">
<title>Document</title>
</head>
<body>
<nav>
<div class="logo">
Tutorials.
</div>
</nav>
<img src="{% static 'main/example.png' %}" alt="My image">
</body>
</html>
The static files called for in index.html do not load. The alt text is seen.
First of all I think you have not configured your static files and media files. Try configuring it as follows. In your settings.py ensure to include STATICFILES_DIR, STATIC_ROOT, MEDIA_URL, MEDIA_ROOT in your settings.py and then add the below lines below STATIC_URL = 'static/'
MEDIA_URL = 'media/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles/'
MEDIA_ROOT = BASE_DIR / 'static/media'
By doing this you are telling django where to get your static files. now your have to add the link of the static files in your project urls.py. you will add that as below.
from django.conf import settings
from django.conf.urls.static import
static
urlpatterns = [
.......
]
urlpatterns +=
static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
One last thing that I assumed you had done is creating static folder in your project root and inside that static folder create media folder where all the images you want to load are.
Now run python manage.py collectstatic
I am trying to deploy my app to heroku.
I successfully deployed to app after dealing with some bugs(the CSS wouldn't load, or images wouldn't load). Now when I deploy the app works fine, when DEBUG = True.
When I change DEBUG = False all the images fail to load.
Here is my code:
settings.py
"""
Django settings for DBSF project.
Generated by 'django-admin startproject' using Django 3.1.2.
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/
"""
from pathlib import Path
import django_heroku
import os
from dotenv import load_dotenv
load_dotenv()
# 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 = os.environ['SECRET_KEY']
AUTH_USER_MODEL = 'social.User'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['desolate-lowlands-74512.herokuapp.com', 'localhost', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'channels',
'social',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'DBSF.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',
],
},
},
]
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
WSGI_APPLICATION = 'DBSF.wsgi.application'
ASGI_APPLICATION = 'DBSF.asgi.application'
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 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'
TIME_ZONE = 'EST'
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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media/')
MEDIA_URL= "/media/"
Here's asgi.py
"""
ASGI config for DBSF project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import social.routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
social.routing.websocket_urlpatterns
)
),
})
here's wsgi.py
"""
WSGI config for DBSF project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')
application = get_wsgi_application()
heres the procfile.windows
web: python manage.py runserver 0.0.0.0:5000
heres the procfile
web: gunicorn DBSF.wsgi
heres layout.html
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script crossorigin src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<script type='text/babel' src="{% static 'social/javascript/react_components.js' %}"></script>
<script type="text/babel" src="{% static 'social/javascript/layout.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie#rc/dist/js.cookie.min.js"></script>
{% block head %}{% endblock %}
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="{% static 'social/styles/base.css' %}">
<link rel="shortcut icon" type="image/png" href="{% static 'social/favicon/favicon.ico' %}"/>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<nav class='main_nav'>
<a href="{% url 'index' %}" title='homepage'>DBSF</a>
<form action="/find_friends" method="GET">
<input name='search_term' type='text' placeholder='Search for friends'>
<input class='search_friends_button' type="submit" value='🔍'></form>
<a href="{% url 'profile' %}">
{% if user.profile_pic.url != '' %}
<img class="profile_pic_small_icon" src="{{user.profile_pic.url}}" alt="profile_pic">
{% else %}
<img class='profile_pic_small_icon' src="{% static 'social/core_images/no_image.jpg' %}" alt="{{user}} hasn't uploaded an image yet">
{% endif %}
{{user|title}}
</a>
Messages
<form class="logout_form" action="{% url 'logout' %}" method="post">
{% csrf_token %}
<a class='logout_a' href="/logout">Log out</a>
</form>
</nav>
<div class="messages">
<h1>{{message}}</h1>
</div>
<div class="side_bar">
<h4>Friend Requests</h4>
<div id="friendship_request_div"></div>
</div>
<div class="main">
{% block body %}{% endblock %}
</div>
<div class="friends_right_div">
<h4>Friends</h4>
<div id='friendship_div'></div>
</div>
<div id='message_box' class='message_box'>
</div>
</body>
</html>
So basically I need to figure out why DEBUG = False doesn't allow the images to load.
Let me know if it is clear what I am asking or if you need any other files to help me!
Thank you
In deployment mode, you need some bucket(e.g, Amazon S3) to store your static (and media) files and serve them from there. Heroku also has some plugins to do so(needs credit card). Heroku doesnot provide any way to do so without a bucket. That is why, they are not rendering. Also with DEBUG=True, all the media files will still vanish after 30 minutes as heroku runs on dynos and dynos refresh after every 30 minutes thus removing all the media files.
Try putting this in your urls.py:
from django.views.static import serve
and this in your urlpatterns:
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
In production you'd typically have nginx or something else serving media files like images. If you just want a quick and dirty way to still see them with DEBUG = True then this should add the media routes to the url patterns.
I am designing a website using django, following the steps of a course that I've enrolled recently. All the code & resources have been provided to me. I'm following each and every step accordingly but the layout of my website is not similar to what I'm following.
I faced similar problem when I was trying on similar project that I tried before the current one. The layout of my website is way too simple. I'm using the latest versions so i guess there maybe something that I've to include. The image is also not displaying on my website.
It would be really helpful if someone let me know what am I missing.
This is what I'm expecting:/
This is what I'm getting:(
This is my main 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">
<!-- 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>Django Website</title>
</head>
<body>
<!--Top bar-->
{% include 'partials/_topbar.html' %}
<!--Nav bar-->
{% include 'partials/_navbar.html' %}
{% 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>
This is my settings.py:-
"""
Django settings for Django_Project project.
Generated by 'django-admin startproject' using Django 2.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
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/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gwdbwxvan^9g5z-r$g9rf=!zeqrvu*2#^uye!ae#95my3dqp&t'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'pages.apps.PagesConfig',
'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 = 'Django_Project.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 = 'Django_Project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/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.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/2.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/2.2/howto/static-files/
STATIC_ROOT= os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'Django_Project/static')
]
You need to collect static files, in your terminal:
django-admin collectstatic
Also here is the official documentation how to handle static files
Unless inside the templates(html files), you did something wrong with extend layout. In that case you might find this link helpful and this
Also if you could provide the code of the HTML files that would be really helpful.
At your settings files at the end add these lines
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I think you have done something wrong with static files and media file path.
Please check your static file path and media path.
For example you should define the following things in settings.py file
# Static files (CSS, JavaScript, Images)
import os
BASE_DIR = os.path.dirname(__file__)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Also, make sure that the static files and media folder present in the project.
You need to import your static folder in each template
{% load static %}
Then you can access your static files and put it for example in image "scr" tag.
src="{% static 'img/your_image.svg' %}"
i am trying to import my static files (css, js etc.) into my django project. But no matter what i am trying it shows me error 500.
I already read the official documentation here https://docs.djangoproject.com/en/1.9/howto/static-files/ , but i just can't see the problem :/ .
What bothers me is that the template import seems to work.
The GET requests i see in the dev console also seem to be legit e.g.:"http://127.0.0.1:8000/static/css/custom.css" where custom.css is in /project_folder/static/css/custom.css .
My folder structure:
myproject
-> static
-->css
--->custom.css
-> templates
-->base.html(where i request the static file)
-> myproject(app)
-->settings.oy
-->urls.py
-> data_handler(app)
-->static
..
Here is my settings.py:
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
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.9/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myproject',
'info_pages',
'data_handler',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'myproject.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 = 'myproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/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.9/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.9/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.9/howto/static-files/
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static/'),
os.path.join(BASE_DIR,'data_handler/static/'),
os.path.join(BASE_DIR,'myproject/static/'),
)
STATIC_URL = '/static/'
STATIC_ROOT= os.path.join(BASE_DIR,'static/')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
the base.html where i import the static files:
{% load staticfiles %}
<!DOCTYPE html>
<head>
<meta name="generator" content=
"HTML Tidy for HTML5 (experimental) for Mac OS X https://github.com/w3c/tidy-html5/tree/c63cc39">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>SMGR: Slime Mold Graph Repository</title>
<link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet">
<link href="{% static "css/sticky_footer.css" %}" rel="stylesheet">
<link href="{% static "css/custom.css" %}" rel="stylesheet">
<link href="{% static "css/expandy.css" %}" rel="stylesheet">
<link rel="shortcut icon" type="image/png" href="{% static "favicon/favicon.ico" %}"/>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
{% block content %}
{% endblock content %}
<div class="spacer-huge"/>
</body>
<footer class="footer" style="left:0px;">
<div class="container" style="margin-top:9px">
<a href="http://www.mpi-inf.mpg.de/departments/algorithms-complexity/">
<img src="{% static "images/mpilogo-inf-wide.png" %}" alt="mpi logo"></a>
<div style="float:right">
<p class="small">
Imprint
</p>
</div>
</div>
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script> <!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="{% static "js/bootstrap.min.js" %}">
</script>
With django 1.9 You have two ways of doing that.
As you're in DEBUG=True, it's your runserver which emulate a server, but you need to serve your statics.
So you can do :
Use django.contrib.staticfiles in your app, and set the good static dir and url (in a list).
Serve them in your root url file just like
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)
When your project will be served by a real server you'll need to do this.
I am trying to run this project on local server and I get the follwoing error:
My url file is as follows:
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from . import views
urlpatterns = [
url(r'^courses/', include('courses.urls', namespace='courses')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.hello_world, name='hello_world'),
]
urlpatterns += staticfiles_urlpatterns()
And this is the views file
from django.shortcuts import render
def hello_world(request):
return render(request, 'home.html')
This is the setting file
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&s5%_8r2y$9%pbnph*xy*%v^a_!vc0bmbqz%(+l#pc#k7n2r)+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'courses',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'learning_site.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 = 'learning_site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
And this is the home.html file
{% extends "layout.html" %}
{% block title %}Well hello there!{% endblock %}
{% block content %}
<h1>Welcome!</h1>
{% endblock %}
this is the template file:
{% load static from staticfiles %}
<!doctype html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/layout.css' %}">
</head>
<body>
<div class="site-container">
<nav>
Home
Courses
</nav>
{% block content %}{% endblock %}
</div>
</body>
</html>
And this is the layout.html file
{% load static from staticfiles %}
<!doctype html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static 'css/layout.css' %}">
</head>
<body>
<div class="site-container">
<nav>
<!-- Home -->
Home
Courses
</nav>
{% block content %}{% endblock %}
</div>
</body>
</html>
Not able to figure out what the problem is. please help. thanks.
You're trying to reverse the url for 'views.helloworld'. But, that's not the name of the url you've defined. That's the view name. Change your urls.py file to:
url(r'^$', views.hello_world, name='hello_world'),
and then use:
Home
I think the problem might be in the urls.py file
Could you try importing the views as
from courses import views
As per Rohits' suggestions above I made the changes and it worked.
Tip: Dont comment out the changes, delete them! Quoting Rohit "Django will try to resolve the {% url %} tags before rendering the HTML page. So, even though you comment that out, it still tries to reverse the url"