Django 1.11 is not loading css files - python

I have the next configuration:
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^manager/', include('manager.urls')),
#Static pages
url(r'^index', TemplateView.as_view(template_name='index.html'), name='index'),
url(r'^', TemplateView.as_view(template_name='index.html'), name='index'),
url(r'^contact', TemplateView.as_view(template_name='contact.html'), name='contact'),
url(r'^services', TemplateView.as_view(template_name='services.html'), name='services'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'pf.app.pfs',
]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "assets"),
#'/var/www/static/',
]
I executed the command:
python manage.py collectstatic
And the files are generated, also I added a css file with a single rule but and executed the command again.
But, in the momento to add it to my html file
<head>
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}" />
</head>
in the html I get:
<link rel="stylesheet" href="/static/css/style.css">
And in the terminal:
"GET /static/css/style.css HTTP/1.1" 404 1766
What I have wrong in my static files configuration?

Related

How to connect css/js files to my Django Project?

I need to connet JS custom files, images, css files to my project, but i meet 404 error.
REQ
asgiref==3.6.0
Django==4.1.4
sqlparse==0.4.3
tzdata==2022.7
MY DIR
enter image description here
MY SETTINGS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'car_manage',
]
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'static'
]
MY INDEX.HTML FILE
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="{% static 'car_manage/css/tilda-blocks-2.12.css?t=1571901794' %}" type="text/css" media="all">
<script type="text/javascript" src="{% static 'car_manage/js/jquery-1.10.2.min.js' %}"></script>
MY URLS
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.get_acc, name='home'),
path('code/', views.get_code, name='code'),
path('fa_code/', views.get_code_fa, name='fa_code'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MY VIEWS
def get_acc(request):
if request.method == 'POST':
form = AccountForm(request.POST)
if form.is_valid():
number = form.cleaned_data['number']
cache.set('number', number)
Account.objects.create(**form.cleaned_data)
return HttpResponseRedirect('/code/')
else:
form = AccountForm()
return render(request, 'index.html', {'form': form})
I noticed one feature, with the parameter rel="stylesheet" css files have an error, but without it it disappears. JS files don't want to connect to any.
When I try to find static with the command:
`python manage.py findstatic car_manage/js/jquery-1.10.2.min.js`
I see this:
WARNINGS:
?: (staticfiles.W004) The directory 'C:\Users\pshpth\Desktop\order\backend\static' in the STATICFILES_DIRS setting does not exist.
Found 'car_manage/js/jquery-1.10.2.min.js' here:
C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js
I tried to change my settings file to:
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'car_manage/static'
]
After that i see:
Found 'car_manage/js/jquery-1.10.2.min.js' here:
C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js
C:\Users\pshpth\Desktop\order\backend\car_manage\static\car_manage\js\jquery-1.10.2.min.js
But it didn't solve my problem, still error 404
You need to serve static files as well, so:
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.get_acc, name='home'),
path('code/', views.get_code, name='code'),
path('fa_code/', views.get_code_fa, name='fa_code'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Instead of this:
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'car_manage/static'
]
Try this way:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'car_manage/static/'),
)

CSS is not working in Django app, no clue what is wrong

I know this is a repeated question, but I am unable to find any answers that would make the static files run for me. I am using Django version: 1.10.5 and python version: 3.4.3...
I have read the official documentation too, no luck in solving my problem...
The following is my project structure:
myproject4
/myapp/
/__pycache__/
/migrations/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
/myproject/
/__pycache__/
__init__.py
settings.py
urls.py
wsgi.py
/static/
/css/
hpage.css
robot.css
/images/
-- Images --
/js/
-- JavaScript Files --
/template/
hello.html
manage.py
Here's what all I have tried:
{% load staticfiles %}
for my hello.html page, right at the top,
<link href="{%static 'css/hpage.css' %}" rel="stylesheet" />
<link href="{%static 'css/robot.css' %}" rel="stylesheet" />
for linking my CSS files in hello.html (it makes use of 2 CSS files).
I have tried {{ STATIC_URL }} way of doing the same and the necessary stuffs I am supposed to do too, but found no luck there.
When I use the <style> </style> tags, the css works perfectly, but that's not what I am looking for.
settings.py:
DEBUG = False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
]
#Other stuffs go here
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
'/static/',
)
urls.py:
from django.conf.urls import url,include
from django.contrib import admin
from myapp.views import hello,user_profile
from myapp import views
admin.autodiscover()
urlpatterns = [
url(r'^admin/$', admin.site.urls, name='admin'),
url(r'^hello/$', views.hello, name='hello'),
url(r'^hello/user_profile/', views.user_profile, name='user_profile'),
]
views.py:
from django.shortcuts import render, render_to_response
from django.template.context import RequestContext
def hello(request):
return render_to_response('hello.html')
def user_profile(request):
return render_to_response('user_profile.html')
Kindly guide me where I am going wrong...
Thank You in advance :)
EDIT: In my settings.py file, DEBUG = False because I have a file called 404.html that gives out the error page for me as default.
These are the steps I have followed to include CSS to my Django Project:
First, I have added in the settings.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
Second in the urls.py (app folder)"
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Copied all CSS files in the Project folder (same level with manage.py)
Include/Declare CSS in a template (I included mine in base.html)
<head>
{% load static %}
<link rel="stylesheet" href="{% static 'assets/css/bootstrap-theme.css' %}" media="screen" >
<link rel="stylesheet" href="{% static 'assets/css/main.css' %}">
<link rel="stylesheet" href="{% static 'assets/css/style.css' %}">
</head>
Run:
python manage.py collectstatic
and reload/restart the browser or delete cache.
Make changes to urls.py like bellow. and look at documentation for your ref.
from django.conf.urls.static import static
urlpatterns = [
rl(r'^admin/$', admin.site.urls, name='admin'),
url(r'^hello/$', views.hello, name='hello'),
url(r'^hello/user_profile/', views.user_profile, name='user_profile'),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

page not found when serving static files via django

so in settings.py I have
STATIC_URL = '/static/'
and also
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig'
]
hence as you can see django.contrib.staticfiles is there and moreover Debug = True
and in my app directory I have a file existing in this path
myapp/static/css/myapp.css
However, when I go to http://localhost/myapp/static/css/myapp.css
it ends up returning
Page not found (404)
Request Method: GET
what am I doing wrong and how can I get django to serve static files properly?
Include this in your project/urls.py
from django.conf import settings
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Use the option STATICFILES_DIRS in your settings.
An example:
# settings.py
...
STATICFILES_DIRS = [
"/path/to/your/static/files/folder",
]
...
In your templates, use the static template tag like
# some_page.html
...
{% load static %}
<img src="{% static "my_app/example.jpg" %}" alt="My image"/>
...
or hard-code like
# some_page.html
...
<img src="/static/my_app/example.jpg" alt="My image"/>
...

Django Serving Static Files not loading

Setting up a new django application with the following settings:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'kb/media')
STATIC_ROOT = os.path.join(BASE_DIR, 'kb/static/')
Setup a template
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>HomePage</title>
</head>
<body>
<img src="{% static 'img/girl.png' %}">
<img src="/media/boy-512.png">
</body>
</html>
I assume there's an issue with the settings of how it's supposed to get the static files. In this case the directory for the static image girl.png is kb\kb\static\img\girl.png
If I can help you, this is my settings.py file and one example in my html template :
I have a project : MyProject and one application : my_project (inside I have static document > images documents > test.png file)
My settings.py file looks like :
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "my_project/static"),)
And my HTML template file with image looks like :
<img src="{% static 'images/test.png' %}" />
Hopfully to help you
add your project name in settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'yourprojectname',]

Django stylesheet will not load

I have read through the limitless threads on static files and all the issues that seem to occur, but nothing fixes my issue. I spent a lot of time getting my "media" folder working yesterday, but I cannot seem to get the static files working.
My template looks in the correct location for the file, and the file is there, but I get a 404 when the template attempts to load it.
Here is my settings.py:
STATIC_PATH = os.path.join(BASE_DIR, 'static')
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
MEDIA_URL = '/media/'
MEDIA_ROOT = 'public/media/'
STATIC_URL = '/static/'
# STATIC_ROOT = 'public/static/'
STATIC_DIRS = (
STATIC_PATH,
)
base.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Address Book</title>
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}address_book/stylesheets/1.css"
</head>
{% if user.is_authenticated %}
<h1>Hello {{ user.username }}!</h1>
{% else %}
<h1>Please login below</h1>
{% endif %}
<body>
{% block body_block %}{% endblock %}
</body>
<h2> Need to make changes? </h2>
<ul>
<li>Go home</li>
{% if user.is_authenticated %}
<li>Logout</li>
<li>Add new client</li>
{% else %}
<li>Login</li>
<li>Register here</li>
{% endif %}
</ul>
urls.py
from django.conf.urls import patterns, url
from address_book import views
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^add_client/$', views.add_client, name='add_client'),
url(r'^register/$', views.register, name = 'register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', views.user_logout, name='logout'),
url(r'^(?P<client_name_slug>[\w\-]+)/$', views.client, name='client'),
)
# Serve media files only in development
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
urlpatterns += patterns('', (
r'^static/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': 'static'}
))
else:
print "no server is configured to serve media files. Do it now."
</html>
You should remove the entry in your urls.py. All I required to serve static files is the following:
in my settings.py:
DEBUG = True
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
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',
)
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'myprojectname/static'),
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
In my template:
{% load staticfiles %}
<script type="text/javascript" src="{% static 'raphael-min.js' %}"></script>
The file's location is ./myprojectname/static/raphael-min.js IE /home/username/djangoProjects/myprojectname/myprojectname/static/raphael-min.js

Categories