Django template: static files in app directory - python

In Django settings.py file we have
STATIC_URL = '/static/'
And in each app directory I have static folder for css, js files.
For example:
├── myapp
│   ├── migrations
│   ├── __pycache__
│   ├── static
│   └── templates
When I use {% static "......." %} in *.html file
For example
<link rel="stylesheet" href="{% static "style/fesahat.css" %}" />
<link rel="stylesheet" href="{% static "style/loginStyle.css" %}" />
In output render django creates URL like this:
mysite.com/static/style/fesahat.css
mysite.com/static/style/loginStyle.css
I want to create the URL like this:
mysite.com/myapp/templates/static/style/fesahat.css
mysite.com/myapp/templates/static/style/loginStyle.css

No you don't. Static files are not templates; don't put them there.

#Daniel Roseman is right. Always use meaning full names.
STATIC_URL = '/static/' #This is URL prefix so use any prefix
Always use name-spacing in each app level static directory.
app1
app1/static/app1/files
app2
app2/static/app2/files
static file namespacing
Now we might be able to get away with putting our static files directly in my_app/static/ (rather than creating another my_app subdirectory), but it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would be unable to distinguish between them. We need to be able to point Django at the right one, and the best way to ensure this is by namespacing them. That is, by putting those static files inside another directory named for the application itself.
You can namespace static assets in STATICFILES_DIRS by specifying prefixes.

The way you use declare the static file is not right,
in your example:
<link rel="stylesheet" href="{% static "style/fesahat.css" %}" />
You are closing the double quotes when declaring the path to your css files,
You should combine double and single quotes like this:
<link rel="stylesheet" href="{% static 'style/fesahat.css' %}" />

Related

Django unable to find javascript static files, not rendering any styling

Feels like I'm missing something basic.
I'm just trying to make an django application of currently nothing but a login page using an html template that has its own css and js. But I'm having weird issues with the statements for linking my static files. No CSS styling is being rendered in my browser, and all of the javascript links get 404 file not found errors on my django server.
This is the <head> of auth-login.html.
{% load static %}
<!doctype html>
<html lang="en">
<head>
<title>Login template from online</title>
<!-- these aren't giving errors -->
<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" />
<!-- these are giving errors for some reason -->
<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 I'm specifying the static files location:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # lpbs_demo/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
The Django project is currently structured with a project app called lpbs_demo and an app called user_auth. The static/ folder is inside of the project app (lpbs_demo/ folder). The templates/ folder is at the project root directory, i.e. at the same level as manage.py
. lpbsnew/
+-- manage.py
+-- lpbs_env/ (venv)
+-- lpbs_demo/ (project app/package)
| +-- __init__.py
| +-- settings.py
| +-- static/
| +-- urls, asgi, wsgi ...
+-- user_auth/ (app)
| +-- migrations/
| +-- admin.py
| +-- views.py
| +-- models, tests, ...
+-- templates/
The project app urls.py in lpbs_demo/ looks like...
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 with this, I'm not sure why only the Javascript files are generating errors and not being found, while the css files aren't generating errors but they're not rendering on the web page at all and I just see text in Times New Roman unstylized. It feels like there's something basic about linking static content that I must be missing.
I've called python manage.py collectstatic already as well.
edit: forgot to include templates/ folder location in the original post.
Edit 2: I got two suggestions on using STATIC_ROOT in settings.py but neither of them are changing the visuals I'm getting.
STATIC_URL = '/static/'
# STATIC_ROOT = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "staticFiles")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
Several messages about potentially overwriting files come out.
Edit 3: It appears that the js files weren't getting copied via the python manage.py collectstatic command for some reason and I wasn't really sure why. But I made a new django project and was able to get that to work.
I'm no longer getting file not found errors, but I'm still not able to get any styling to render for some reason, so I made a new question.
Django not serving static files and not stylizing anything
Move the static directory to the same level as the manage.py file.
BASE_DIR means the outermost folder of your project. So, this— os.path.join(BASE_DIR, 'static')—would return a path like lpbsnew/static/. Django is trying to find a folder called static inside lpbsnew but it isn't there.
I try to sort it out step by step (I personally had a hart time to sort out all the aspects of paths, urls, reverses and dev/deployment in a django app):
BASE_DIR should (by convention) point to the base folder which is lbpsnew in your case.
your assigment is doing that, but the comment is wrong! It does not point to lpbs_demo but to lbpsnew!
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # lpbs_demo/
Btw, in most of the django projects lpbs_demo would be called lpbsnew (lbpsnew_project/lbpsnew/lbpsnew/settings.py)
STATIC_ROOT is the (absolute) target path where "collectstatic" will copy all your static files to.
Please check after running "collectstatic" if files are there.
it is a difference if you run your app with "runserver" or Apache etc. Why?
3a) because in Apache you could have Alias defined (which might be the problem) or a missing access right to the static folder.
3b) it makes a difference if you have DEBUG = True/False in your settings.py
... so please provide more details.
For Debugging:
you can use the print(str(BASE_DIR)) to check directly in the seetings.py file.
you can display the page source code in the browser and check what {% ulr ... %} has done in your html file
missing css (files, individual items) never lead to error messages to my experience. Style is then just missing. Carefull to empty Browser cache if you change css file content!

django won't load staticfiles from statifiles_dirs

My style.css is placed in appname/static/appname/.
My settings.py has this code:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static/"),
)
And in my base.html I load it like this:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'appname/style.css' %}">
But the styles are not loading.
If I remove STATICFILES_DIRS and change STATIC_URL = '/static/' to STATIC_URL = '/static/appname/', it works perfectly, but I guess it's not the best practice for the case I'll add any other app to the project later. What I might be doing wrong?
Just change one thing,
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
It will search in static folder inside your app. Also if you want to add a specific directory,
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"), '/your specific directory/',
)
From here you can directly add the particular file name, and djnago will search in that specific directory.
Remove "appname" in {% static 'appname/style.css' %}, you must not place it there because python knows automatically in which application the file is, it get the application name from the request
By default django picks static directory from app's directory. So, if your static directory is inside app directory there is no need to specify STATICFILES_DIRS.
Now /static/ will point to files and directories in the static directory of your app. To refer your css file use
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'appname/style.css' %}">

Django static files not found Value error

I'm working on a project using cookiecutter django template: https://github.com/pydanny/cookiecutter-django
The project is run in docker containers that come with the cookiecutter-django template on ubuntu 16.04LTS.
When trying to get the site to production, it returns the following error on some pages:
the file 'events\css\themes\fontawesome-stars.css' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f830be38ac8>.
folder structure is:
./project/events/static/
└── events
├── css
   ├── details.css
   ├── list.css
   └── themes
   ├── fontawesome-stars.css
  └── fontawesome-stars-o.css
No errors are reported during docker build process and after that running collectstatic.
Permissions for the files on the server are set to 775.
static config in base.py config:
# STATIC FILE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = str(ROOT_DIR('staticfiles'))
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url
STATIC_URL = '/static/'
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
STATICFILES_DIRS = [
str(APPS_DIR.path('static')),
]
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
In template I'm including the file like this.:
{% load static %}
{% load crispy_forms_tags %}
{% block title %}
{% endblock%}
{% block css %}
{{block.super}}
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="{% static 'events\css\themes\fontawesome-stars.css' %}">
{% endblock %}
How are you including the static files on your templates? It looks you are specifying the path directly. Instead you should use:
{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'events/css/themes/fontawesome-stars.css' %}">
Because in production whitenoise and collectstatic command will add extra content to the file name for versioning, caching and other purposes.

Fetch Static files from Server in Django

I'm using a development server for django. I want to grab my static files from a server. htts://www.example.com/static
How do I do this in Django?
Currently I'm trying to to change the STATIC_URL from '/static/' , but it fails whenever I change it. By fail I mean that the html still loads, but the site can't access and load my static files.
this is the url of the static that will be used in template STATIC_URL = '/static/'
add the desire path to the static files dirs var
STATICFILES_DIRS = ('/var/www/my_site/my_path',)
please note that the path doesn't end with backslash
please note that the trailing comma
now in your templates use
<head>
{% load staticfiles %}
<link href="{% static "css/style.css" %}" rel="stylesheet">
</head>
this link will resolve to my_site/static/css/style.css
and will be in the folder /var/www/my_site/my_path/css/style.css
href="my_site/static/css/style.css"
maps to
STATICFILES_DIRS : /var/www/my_site/my_path/css/style.css

Django isn't serving static files, getting 404 errors

I can't seem to get my static files to load from my templates. I've followed the official documentation but I must be missing something.
My directory layout (generated by Django, most files omitted):
myproject
myproject
settings.py
urls.py
static
css
bootstrap.css
main.css
templates
base.html
myapp1
myapp2
...
manage.py
My settings.py:
STATIC_URL = 'static/'
I'm referencing my stylesheets like so (from my templates):
{% load staticfiles %}
<link rel="stylesheet" href="{% static "css/bootstrap.css" %}" type="text/css">
<link rel="stylesheet" href="{% static "css/style.css" %}" type="text/css">
Which gives this once rendered (in HTML):
<link rel="stylesheet" href="static/css/bootstrap.css" type="text/css">
<link rel="stylesheet" href="static/css/style.css" type="text/css">
Yet these links don't actually lead anywhere (when I visit them I get 404 error from Django). I feel that I could fix this by adding something in urls.py, but I thought Django did this automatically when you run the server? What am I missing?
Have you defined your static files directory in settings.py ?
I'm guessing you have 'django.contrib.staticfiles', in your installed apps.
If you haven't defined your static files dir, you could by doing something like this:
import os.path
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
STATICFILES_DIRS = (
os.path.join(PROJECT_ROOT, 'static'),
)
This is the working solution for static/media/template access in django for windows,
settings.py
import os.path
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join('static'),
)
My problem was solved by adding "STATICFILES_DIRS" in settings.py file
STATIC_URL = '/static/'
STATICFILES_DIRS = ( os.path.join('static'), )
I thought Django did this automatically when you run the server?
Why did you think that? If you've followed the official documentation, you won't have found that. Read what you have to do to serve them in development here.
There's another problem. Your STATIC_URL is a relative link, so browsers add it to the existing page URL. So if you're on page /foo, 'static/css/style.css' evaluates to /foo/static/css/style.css'.
Make sure it either starts with / - ie /static/ - or is a full URL, ie http://myserver.com/static/.
Check if STATICFILES_FINDERS is defined in your settings.py
https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_FINDERS
The default value of STATICFILES_FINDERS is good enough but you have 2 choices :
you need to have the static file inside an app and having this app in your INSTALLED_APPS
or you need to define STATICFILES_DIRS with your path to the static files if expect the behavior being the one of django.contrib.staticfiles.finders.FileSystemFinder
I encountered this problem too. And I solved the problem by revising the href like this:
<html>
<link rel="stylesheet" href="{{STATIC_URL}}css/bootstrap.css" type="text/css">
<link rel="stylesheet" href="{{STATIC_URL}}css/style.css" type="text/css">
</html>
Make sure that you have the static folder set up in the right place, that is if it is in the app folder, then you can get further clarification from this helpful resource1.
My solution was DEBUG = True in settings.

Categories