Python 2.7 Django 1.9 static files administration error - python

I am trying to solve this for 2 hours now. I tried everything I read every post but I think I am still missing something. My static files are not loading. I am getting this error when I click to static files url path on browsers view-source page. "A server error occurred. Please contact the administrator." Before this error It was fine in this index page; 127.0.0.1:8000/ But when I try to go on 127.0.0.1:8000/home it was still same index page but it wasn't loading static files because it was looking static files at home/ directory. So I decided to make my static urls dynamic. I though I was not making mistake but Pycharm says unresolved template reference to this;
<script src="{% static 'jquery.min.js' %}"></script>
<script src="{% static 'bootstrap.min.js' %}"></script>
<script src="{% static 'retina-1.1.0.js' %}"></script>
<script src="{% static 'jquery.hoverdir.js' %}"></script>
<script src="{% static 'jquery.hoverex.min.js' %}"></script>
<script src="{% static 'jquery.prettyPhoto.js' %}"></script>
<script src="{% static 'jquery.isotope.min.js' %}"></script>
<script src="{% static 'custom.js' %}"></script>
at the begining of the page I used
{% load static from staticfiles %}
this peace of code. How can ı fix these problems guys I need your help!
Debug = true
urls.py
from django.conf.urls import url, include
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^home/$', views.index, name = 'home'),
url(r'^$', views.index, name= 'index'),
url(r'^second/$', views.second, name = 'second'),
]
if settings.DEBUG:
urlpatterns +=[
url(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root', settings.STATIC_ROOT}
),
]
Settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'basic/static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'assests/')

Within the django docs for 1.9 the stated way of serving static files during development is to use the following:
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)
Along with the following in your templates:
{% load staticfiles %}
<img src="{% static "my_app/myexample.jpg" %}" alt="My image"/>
Have you tried using this method of serving static files whilst in debug?

Related

Django 404 css file

For a long time I tried to solve the problem with loading all my static files. When I found a working solution, all svg started loading, but css files didn't.
Here is my settings.py (showing you only main things)
import mimetypes
mimetypes.add_type("text/css", ".css", True)
BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = False
STATIC_URL = '/static/'
if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
else: STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Here is my urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.conf import settings
from django.views.static import serve
urlpatterns = [
path('', include('main.urls')),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
Here is an example of using css files in my templates
{% load static %}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-v4-grid-only#1.0.0/dist/bootstrap-grid.min.css">
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
<link rel="stylesheet" type="text/css" href=" {% static 'css/main.css' %}">
And this is the error in Chrome Console
Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
And also i cant open css files in a new tab. I am getting that error
Also, if you remove %20 from the address bar, then I will open the css file
P.S.
I am trying to deploy it
1- Try to replace a slash forward path
<link rel="stylesheet" type="text/css" href=" {% static '/css/reset.css' %}">
2- whitenoise
pip install whitenoise
Then, set it to "MIDDLEWARE" in "settings.py". Finally, CSS is loaded successfully:
MIDDLEWARE = [
# ...
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", # Here
# "whitenoise" will solve "MIME type" error then CSS is loaded successfully:
]
3- change your static URL like that:
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)
I think your mistake is that you put in a space in front of your static link
<link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}">
Try removing the space in front of {% so it will become
<link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}">
%20 is translated to a space character in URL's, so that why I think that's the issue

Django not serving static files and not stylizing anything

I downloaded a template in the form of a zip file on my machine. It has a file for a homepage, auth-login.html. If I load this on its own then it loads correctly, I see styling and I don't get any console errors.
But it seems like I can't get this template to load its css and styling in my Django project via python manage.py runserver with DEBUG=true. I'm trying to just get this on a development server and I haven't really been able to get past step 1. When I try to go to my application's home page, I see unstylized times new roman text in my browser. No styling loads on the page at all. I'm not getting server/console errors either.
My Django project is of the following structure
lpbsproject/
project_root/
staticFiles/ (STATIC_ROOT, where collectstatic copies to)
project_app/
settings.py
urls.py
wsgi.py, asgi.py, __init__.py...
static/ (STATIC_URL, original location of static files)
assets/ (this folder is copied/pasted from the template .zip)
css/, js/, ...
user_auth/
migrations
views.py
admin.py, models.py, apps.py, test.py ...
templates/
manage.py
Here's the <head> of my html file with all the <link> and <script> statements. These currently aren't generating errors.
{% load static %}
<!doctype html>
<html lang="en">
<head>
<title>Login template from online</title>
<link rel="shortcut icon" href="{% static 'assets/images/favicon.ico' %}">
<link href="{% static 'assets/css/bootstrap.min.css' %}" id="bootstrap-style"/>
<link href="{% static 'assets/css/icons.min.css' %}" type="text/css" />
<link href="{% static 'assets/css/app.min.css' %}" id="app-style" type="text/css" />
<script src="{% static 'assets/libs/jquery/jquery.min.js' %}"></script>
<script src="{% static 'assets/libs/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
<script src="{% static 'assets/libs/metismenu/metisMenu.min.js' %}"></script>
<script src="{% static 'assets/libs/simplebar/simplebar.min.js' %}"></script>
<script src="{% static 'assets/libs/node-waves/waves.min.js' %}"></script>
<script src="{% static 'assets/js/app.js' %}"></script>
</head>
In settings.py, this is how BASEDIR and the static file location are specified
BASE_DIR = Path(__file__).resolve().parent.parent # points to project_root/ directory
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticFiles')
There's ~1200 files in project_root/static/assets/ and I am seeing these get copied into project_root/staticFiles from python manage.py collectstatic. Last night I was dealing with some weridness where none of the js files were getting copied via the collectstatic command.
and urls.py for curiosity sake...
from django.contrib import admin
from django.urls import path
from django.contrib import admin
from django.urls import path, include
from user_auth import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.userLogin, name='loginHome'),
path('login', views.userLogin, name='login'),
path('logout', views.userLogout, name='logout'),
path('registration', views.userRegistration, name='registration'),
path('dashboard', views.dashboard, name='dashboard'),
]
So if python manage.py collectstatic is working... why am I still not able to see any styling at all? I'm not really sure what's going wrong here. It's felt way too difficult to just get a simple /static/ folder working for this project.
The terminal using python manage.py runserver isn't even showing requests for most of these css or js files. I just see
[24/Nov/2020 12:48:00] "GET / HTTP/1.1" 200 7194
[24/Nov/2020 13:25:39] "GET /static/assets/libs/bootstrap/js/bootstrap.bundle.mi
n.js.map HTTP/1.1" 404 1883
[24/Nov/2020 13:25:39] "GET /static/assets/libs/metismenu/metisMenu.min.js.map HTTP/1.1" 404 1853
[24/Nov/2020 13:25:39] "GET /static/assets/libs/node-waves/waves.min.js.map HTTP /1.1" 404 1844
I was able to get an answer when I posted about this on django forums.
No one here caught the html errors. I was inconsistently using type=text/css and rel='stylesheet'. Also <link> tags can end with >, not />.

Django Will Not Open Up Static File Image, Django 3

So I have been trying to figure out why the image will not show and I have watched and read numerous things, but i still can't find anything. This is my first question on here. Thanks for helping out
HTML
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Nikhil's Portfolio</title>
</head>
<body>
test
<img scr="{% static 'static/homepage/wpap.jpg' %}" alt="why is it not working">
<img scr="{% static 'static/homepage/download.jpg' %}" alt="why is it not working">
</body>
</html>
url.py of my website (not app url)
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('admin/', admin.site.urls),
path('', include('homepage.urls'))
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
How my files are arranged
img of file organization
Try this
{% static 'homepage/wpap.jpg' %}
Instead of
{% static 'static/homepage/wpap.jpg' %}
It would need to change from this:
<img scr="{% static 'static/homepage/wpap.jpg' %}" alt="why is it not working">
To this:
<img src="{% static 'static/homepage/wpap.jpg' %}" alt="why is it not working">
The "scr" would change to "src"

Django not finding static js scripts in the correct folder

I've already run collectstatic and created the static directory in my urls.py, and all other static files work fine (bootstrap, the custom CSS) and other scripts in the same directory work perfectly fine.
This is the error code in the console.
Failed to load resource: the server responded with a status of 404 (Not Found) ... jquery.formset.js:1
(http://localhost:8000/static/js/django-dynamic-formset/jquery.formset.js)
(index):86 Uncaught TypeError: $(...).formset is not a function
at (index):86
For the second error, I've run into a similar problem before. Moving the jQuery CDN tags above the script itself solved the issue then, but it's not working now.
This is my root urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('showroom/', include('showroom.urls')),
path('', RedirectView.as_view(url='/showroom/', permanent=True)), # Redirect homepage to showroom
path('accounts/', include('allauth.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
# Static and media files
STATIC_URL = '/static/'
STATIC_ROOT = (
os.path.join(BASE_DIR, 'static')
)
MEDIA_URL = '/media/'
MEDIA_ROOT = (
os.path.join(BASE_DIR, 'media')
)
Django html
{% block scripts %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
{% load static %}
<script src="{% static '/js/django-dynamic-formset/jquery.formset.js' %}"></script>
{% endblock %}
This is the script section from the rendered html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/static/js/django-dynamic-formset/jquery.formset.js"></script> <script type="text/javascript">
$('.formset_row-image_set').formset({
addtext: 'add another',
deleteText: 'remove',
prefix: 'image_set',
});
</script> </body>
For context, this is an object creation form. The script allows dynamically created server-side formsets so users can upload individual images.
If there's any additional context necessary, just let me know.
Django handles static files in its own way you do not need to provide the full path to the location.
Try replacing with this line:
<script src="{% static 'js/django-dynamic-formset/jquery.formset.js' %}"></script>
also make sure you added on top of your file {% load static %}
As per documentation : https://docs.djangoproject.com/en/2.2/howto/static-files/#configuring-static-files

Angular serve working, Angular build not updating files

I'm running a project with an Angular front-end and a Django back-end. Today when I changed some code in the templates the ng build didn't update. I have discovered that it neither updates template changes nor component changes. However, when I run ng serve instead and go to 127.0.0.1:4200 instead of the Django port 8000 the new updates versions are rendered.
The way I have it set up is that I have a template that Django points to with TemplateViev :
{% load static %}
{% csrf_token %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularWebapp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<app-root></app-root>
{% block javascript %}
<script type="text/javascript" src="{% static 'runtime.js' %}"></script><script type="text/javascript" src="{% static 'polyfills.js' %}"></script><script type="text/javascript" src="{% static 'styles.js' %}"></script><script type="text/javascript" src="{% static 'vendor.js' %}"></script><script type="text/javascript" src="{% static 'main.js' %}"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
{% endblock %}
</body>
</html>
And the static directory layout looks like this in settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'angular', 'static'),
os.path.join(BASE_DIR, 'angular-webapp', 'dist', 'angular-webapp'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
And urls.py:
from django.contrib import admin
from django.urls import path, re_path, include
from django.views.generic import TemplateView
from rest_framework import routers
from authentication.views import AccountViewSet, LoginView
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib.staticfiles import views
router=routers.SimpleRouter()
router.register('accounts', AccountViewSet)
class IndexView(TemplateView):
template_name = 'index.html'
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include(router.urls)),
re_path(r'^api/v1/auth/login/$', LoginView.as_view(), name='login'),
re_path(r'^.*/$', IndexView.as_view()),
path('', IndexView.as_view()),
]
Which is the only place I have static files, and which is where the files from ng build is put, IE. the static load loads the runtime.js etc. from the folder where it's output when i ng build.
However, from yesterday the changes I make to my app in the angular-webapp/src/app folder doesn't get updated when I ng build. I have tried removing the dist folder to create a fresh one, but that doesn't change anything. When it comes back and I run the project it still somehow uses the old layout while ng serve works perfectly.
Is it something about how ng build works that I am missing?
It's probably a cache busting issue : your files still have the same name, and since they're cached by the browser, it doesn't reload them.
consider building with the --prod flag, which contains several other flags such as --aot, but to correct your issue, try building with --output-hashing=all.
Directly from ng build --help :
--output-hashing=none|all|media|bundles
(String) Define the output filename cache-busting hashing mode.
aliases: -oh <value>, --outputHashing <value>

Categories

Resources