django static file : The requested resource was not found on this server - django

my html
<!DOCTYPE html>
{% load static %}
<html>
<head>
<title>Fish store</title>
<link rel="stylesheet" type="text/css" href="{% static 'css/animate.css' %}">
</head>
<body>
<h2>Home page</h2>
</body>
</html>
my settings.py
INSTALLED_APPS = [
'fish.apps.FishConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
in fish app I have static folder and css folder, and then animate.css
fish/static/css/animate.css
main url
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index)
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Now I try to access http://localhost:8000/static/css/animate.css
it shows:
Not Found
The requested resource was not found on this server.

Related

Staticfiles not loading on Django

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

django static files 404 error after migration

static folder path correct and it was all working before migration.
index.html
{%load staticfiles%}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="{% static "css/mycss.css"%}"/>
<title>My first Django App</title>
</head>
<body>
<h1>{{somthin}}</h1>
<img src="{% static 'images/zoro.jpg'%}" alt="Oops!No Image">
</body>
</html>
after python manage.py runserver in terminal static files are showing 404 error.
make sure all these configuration you have in your settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
and in main urls.py
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and use {% load static %} tag in templates, also if you use double quote outside curly brackets, use single quote inside
<link rel="stylesheet" href="{% static 'css/mycss.css' %}"/>

static image/media files in django

i am unable to load static files with django in my template my files are shown below
Settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Theme'
]
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIR = [
STATIC_DIR,
]
Template/index.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First App</title>
</head>
<body>
<h1>Hello this is index.html!</h1>
<img src="{% static 'images/mark.jpg' %}" alt="My image">
</body>
</html>
project Direstory
This is the projec t directory`
Add these code also in your main url file
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and in setting add this line too
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")
STATICFILES_DIR list should be named STATICFILES_DIRS.
In development when you run with runserver and DEBUG=True it is enough.
To serve staticfiles in production:
usage of external web-server (in production you will most probably have one or web-proxy in front of django) is recommended. Call collectstatic
and serve the resulted static_root dir with web-server
Or you can upload them to CDN (AWS S3, CLoudflare)
Or it is possible to make django serve them using Whitenoise
least recommended but still possible - serving with django as is development by adding static urls

Django static files are not loading

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.

When trying to run a Django project I get the NoReverseMatch error

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"