Django stylesheet will not load - python

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

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/'),
)

Django media files not loading

I have a users app, profile is a model created in its models.py.The image is present in /media/profile_pics/ but even after giving the full path in src it is not loading. I cannot figure out why.Adding the relevant files below.
models.py
from django.contrib.auth.models import User
from django.db import models
from django.contrib.auth.models import AbstractUser
class profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='media/default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
profile.html
<!DOCTYPE html>
{% extends 'base2.html' %}
{% load crispy_forms_tags %}
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile</title>
</head>
{% block content %}
<body style="margin-left: 300px">
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<img class="rounded-circle account-img" src="E:\py-projects\hello-world\media\profile_pics\profile1.png">
</div>
</div>
</body>
{% endblock %}
</html>
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
print(MEDIA_ROOT)
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
urls.py(the main urls.py, not of app users)
from django.contrib import admin
from django.urls import path, include
from users.views import profile
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('users.urls'), name='index'),
path('profile/', profile, name='profile'),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
i feel stupid for not seeing this :| had to add this.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Use this in your urls.py
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve, {'document_root':
settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve, {'document_root':
settings.STATIC_ROOT}),
]
And in your settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'

Django STATIC files does not work in Develop mode

Django STATIC files does not work in Develop mode.
I tried in many ways, but I did not succeed.
Could someone tell me where I'm wrong?
Thank you very much for your attention.
STATIC_URL = '/static/'
STATIC_ROOT = "/Users/user/Projects/RMA/static/"
STATICFILES_DIRS = (
os.path.join(BASE_DIR, '..', 'static'),
)
....
'django.contrib.staticfiles',
routes
urlpatterns = [
url(r'^$', views.index, name='index')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
View
def index(request):
return render(request, 'base.html', {'question': 'ads'})
template
{% load static %}
<link href="{% static 'site/bower_components/select2/dist/css/select2.min.css' %}" rel="stylesheet">

Python Django (static files/change ip server)

I have one problem. When i change ip adress for server, then my css (Bootstrap) don't work.
urls.py:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Project.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^home/', 'Blog.views.my_blog')
)
if settings.DEBUG == True:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
base.html
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head lang="ru">
<title> Savichev's site </title>
<!-- Bootstrap -->
<link rel="stylesheet" href={% static "css/bootstrap.css" %}>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<meta charset="UTF-8">
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
What's wrong ?
CSS work correctly only on ip 127.0.0.1:8000
I suppose, with the little information you gave us, you need to provide a STATIC_ROOT variable in your settings.py.

Django: STATIC_URL adds appname to the url

I have configured my static settings like so:
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
('js', os.path.join(STATIC_ROOT, 'js')),
('css', os.path.join(STATIC_ROOT, 'css')),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
and these in my urls.py:
urlpatterns = patterns('',
url(r'^login/?$', login, name='login'),
url(r'^logout/?$', logout_then_login, name='logout'),
url(r'^profile/(?P<user_id>\d+)$', 'profiles.views.detail'),
url(r'^profile/edit$', 'profiles.views.edit'),
)
urlpatterns += staticfiles_urlpatterns()
It works very well for the url localhost:8000/login, but when I get to the localhost:8000/profile/edit site, which is handled by my profiles App, the {{ STATIC_URL }} changes all the paths from /static/... to /profile/static/..., so my javascripts and stylesheets are not found any more.
What'd I do wrong?
EDIT: Here would be my base.html
<!DOCTYPE html>
<html>
<head>
<title>Neighr{% block title %}{% endblock %}</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery.min.js"></script>
{% block script %}{% endblock %}
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
Since you're using the django built-in developement server, try to remove the following line from your urls.py:
urlpatterns += staticfiles_urlpatterns()
In production, you'de better not serve static files with django, so use the collectstatic command.
edit
If settings.py, try something like this:
STATIC_ROOT = os.path.join(os.path.dirname(__file__), '../../static')
STATIC_URL = '/static/'

Categories