Django: Where to store global static files and templates? - python

So I am working on a Django (1.9) project, and have the need to use the same templates and static files across multiple apps. I know how to use templates and static files stored outside each app (using STATICFILES_DIRS and TEMPLATEFILES_DIRS in settings.py), but where should I store them?
My guess would be in folders in the project directory.
home/user/myproject/staticfiles
home/user/myproject/templates
But if there are official reconsiderations (which I have been unable to find in the documentation), I would prefer to comply with those.
Also, if there are any other recommendations for using templates and static files outside of the normal django app directories, that you think I should know about, I'd really appreciate you telling me (or telling me where to look).
Cheers :)

Assume there is a global css file located here:
home/user/myproject/staticfiles/css/global.css
Change settings.py to match this:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "staticfiles"),
]
Inside of a template, for example, index.html:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/global.css' %}" />
Now Django can find global.css.

in your settings.py file add the following
STATIC_URL = '/static/' # this will be added before your file name
STATIC_ROOT = 'path/to/your/files/' # this will help django to locate the files
read more about it here: https://docs.djangoproject.com/en/1.9/howto/static-files/

While nu everest's answer is correct and working (after you restart the server), in my case it lacks the advantage of my IDE autosuggesting the static files' paths. So I went for specifying a relative path inside my project. For simplicity I named the directory 'static' (same as the STATIC_URL variable) but of course any name is possible.
settings.py:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
"myproject" + STATIC_URL
]
What's important here: The root is actually not the settings.py's parent, but its parents's parent, as in:
BASE_DIR = Path(__file__).resolve().parent.parent

Related

Unable to connect background Image with static file Django

I have following html template
<div class="owl-slide cover" style="background-image: url({% static 'img/slides/slide_home_2.jpg'%});">
</div>
But I am not able to load static background.
my static directory is same as it is in django project path along with templates.
here is my part of setting.py for static files
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/',)
Everything seems look ok but my background is not working any suggestion will be helpful
Sorry to hear that. I don't know if you have solved you issue meanhwile.
In my settings.py I have the following STATIC setting
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Within every Django-App in my Django-Website I have a directory like this
<app-name>/static/<app-name>/...
And within the templates I am using the following code:
At the very beginning
{% load static %}
What I also recognized in your code is that your path starts with "img/"
If I want to refer to an image then I use
{% static "<app-name>/image.png" %}
at least when deploy on a server I have to execute the following command so Django collects all static files and make it available.
python manage.py collectstatic
Maybe this helps?

How to add my own files to django 'static' folder

I've read django static files document and made my django static files settings like this
setting.py
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_PATH, 'static')
STATIC_URL = '/static/'
html page
<img src="{% static "admin/img/author.jpg" %}" alt="My image"/>
So if I address one of django default static files, it works fine. But if I add my own file and folders to the static folder, it doesn't show it.
I tried
python manage.py collectstatic
But nothing changed. How can I make it work?
A few things...
STATICFILES_DIRS = (
'path/to/files/in/development',
)
STATIC_ROOT = 'path/where/static/files/are/collected/in/production'
When DEBUG = True, Django will automatically serve files located in any directories within STATICFILES_DIRS when you use the {% static 'path/to/file' %} template tag.
When DEBUG = False, Django will not serve any files automatically, and you are expected to serve those files using Apache, Nginx, etc, from the location specified in STATIC_ROOT.
When you run $ manage.py collectstatic, Django will copy any and all files located in STATICFILES_DIRS and also files within any directory named 'static' in 3rd party apps, into the location specified by STATIC_ROOT.
I typically structure my project root as such:
my_project/
/static_assets/ (specified in STATICFILES_DIRS)
/js
/images
/static (specified in STATIC_ROOT)
I hope that helps you understand how the staticfiles app works.
STATIC_ROOT is where files are collected and moved to when collectstatic runs.
If you want files to be consolidated to there they should be found by the static file finder.
As an example, include the following in your settings
STATICFILES_FINDERS = ("django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder")
now for one of the apps that are a part of your project, create a folder called static and put something in it.
When you run collectstatic you should see that file mentioned and it copied to your STATIC_ROOT
You can try adding
STATICFILES_DIRS = (
STATIC_PATH,
)
to your settings.py.
Also, if you haven't already, make sure to include
{% load static from staticfiles %}
in each of your templates where you wish to reference static files.
Lastly, make sure that the file you are referencing actually exists and the file path to it is correct.
Try to:
<img src="{{ STATIC_URL }}admin/img/author.jpg" alt="My image"/>
And in your view must be something like this:
...
from django.shortcuts import render_to_response
from django.conf import settings
def my_view(request):
...
static_url = getattr(settings, 'STATIC_URL')
...
return render_to_response(
template_name,
RequestContext(request, {
'STATIC_URL': static_url,
}))

Django 1.4 serving media files works, but not static

I am using Django 1.4 and for some reason i am able to serve media files, but not the static ones...
Here is my code:
settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
ADMIN_MEDIA_PREFIX = '/static/admin/'
urls.py:
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT}),
base.html:
<link href="{{ STATIC_URL }}css/bootstrap.css" rel="stylesheet">
<link href="{{ MEDIA_URL }}css/bootstrap-colorpicker.css" rel="stylesheet">
i get a 404 http not found... what am i doing wrong? An i did create the static folder in my project right next to media
http://mysite.com:8000/static/css/bootstrap.css
Your static folder should be under one app that you use it for.
For example, I have a project named my_project and an application named my_app, I have some static files used in my_app so I put them under ~/project_path/my_project/my_app/static
NB: my_app must be in INSTALLED_APPS. See STATICFILES_FINDERS documentation.
Edit:
As a best practice, you should have a global static folder in one app (the main one), for example a static folder how contains your html template basic resources as jquery, bootstrap, your global style.
And for the static files how's required only for one app, for example app foo, these files should be under foo/static folder
I suggest removing the explicit media and static views and allowing the staticfiles app to create them (when DEBUG is True under development).
Check the default finders are present in your settings.py
https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_FINDERS
Either add your project static directory to STATICFILES_DIRS (https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS) or place app specific static folders under each app. The app needs to be listed in the INSTALLED_APPS for the finders to locate the static content.
Do not place static files into STATIC_ROOT yourself. This directory is managed by the collectstatic command. See https://docs.djangoproject.com/en/dev/howto/static-files/#deployment
Here is how i define my media url in settings.py:
import os
ABSOLUTE_PATH = os.path.dirname(__file__)
MEDIA_ROOT = os.path.join(ABSOLUTE_PATH, '../media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(ABSOLUTE_PATH, '../static')
STATIC_URL = "/static/"
So like you see the difference is ../media and ../static
Is mysite in your installed apps ? Django look inside your installed apps and check if there's a static folder there.

How can I add css/image on webpage using django?

I put the image("hi.png") and css file in /home/user1/djangoblog/blog/static
In templates i have <img src="{{ STATIC_URL }}images/hi.png" />
I edited the settings.py =>
STATIC_ROOT = ''
STATIC_URL = "/static/"
STATICFILES_DIRS = (
"/home/user1/djangoblog/blog/static/",)
The web page source returns =>
<div><img src="/static/images/a.jpg" /></div>
If the views.py => The image is not displayed on the web page.
now = datetime.datetime.now()
#return render_to_response('current_datetime.html', {"foo": now}, context_instance=RequestContext(request))
t = loader.get_template('current_datetime.html')
c = Context({'foo': now})
return HttpResponse(t.render(c))
But if the views.py => it displays the images on the web page.
return render_to_response('current_datetime.html', {"foo": now}, context_instance=RequestContext(request))
It looks like it's a problem with HttpResponse or RequestContext. How can i fix this problem with HttpResponse or RequestContext?
You need to read the staticfiles docs more carefully.
You specify the absolute path to your static directory with STATIC_ROOT and the URL that directory can be accessed at through a browser via STATIC_URL. Your main static directory should never go in STATICFILES_DIRS. That setting is only to allow you to specify additional directories that should be processed while running the collectstatic management command.
In general, you never use your actual static directory. In development Django serves files from each app's static directory and any directories in STATICFILES_DIRS (excluding the main static directory). In production, you run the collectstatic management command and then setup your main webserver (Apache, Nginx, etc) to serve files from STATIC_ROOT. Django never serves anything from the main static directory (STATIC_ROOT).
I suspect the problem is that you don't have the staticfiles context processor in your settings file. That's the reason that /static/ isn't being inserted where you've put {{ STATIC_URL }}.
It's as simple as putting
'django.core.context_processors.static',
Into the list of context processors (TEMPLATE_CONTEXT_PROCESSORS) in your settings.py file.
Update
I added this in TEMPLATE_CONTEXT_PROCESSORS but still that didn't work. – guru 3 hours ago
Adding 'django.core.context_processors.static' to the list of context processors did fix your problem because as you can now see, it is inserting the value for STATIC_URL wherever it sees {{ STATIC_URL }} in your templates. The error is that you've changed the value of STATIC_URL to "/home/user1/djangoblog/blog/static/" probably because you've been confused by some of the answers here.
Change the value of STATIC_URL back to '/static/' so that line should read
STATIC_URL = '/static/'
That will fix your problem.
Django templates simply put whatever is in the variable into the template. They don't care what it is or what it represents. If the value of STATIC_URL is /home/user1/djangoblog/blog/static/ then it dutifully inserts /home/user1/djangoblog/blog/static/ wherever it sees {{ STATIC_URL }} which is why you are seeing
<img src="/home/user1/djangoblog/blog/static/images/a.jpg" />
whenever it renders the template containing <img src="{{ STATIC_URL }}images/a.png" />

Django staticfiles app help

I've having a little issue with Django's staticfiles app.
I have added
'django.contrib.staticfiles',
to my INSTALLED_APPS and have added
STATIC_URL = '/static/'
STATIC_ROOT = '/Users/kevdotbadger/django/mylook/static/'
to my settings.py file.
All my static files are located within the STATIC_ROOT folder on my Mac.
Now, within my template I use
{{ STATIC_URL }}
which correctly renders to /static/.
However
{{ STATIC_URL }}css/style.css
result in a 404 error. I'm using the 'runserver' command as the server.
Is there something I'm missing?
I implore you to read the howto docs here: http://docs.djangoproject.com/en/dev/howto/static-files/
In short: STATIC_ROOT is only used if you call the collectstatic manangement command. It's not needed to add the directory to the STATICFILES_DIRS setting to serve your static files!
During development (when the automatic serving view is used) staticfiles will automatically look for static files in various locations (because you call its "serve" view with a path to a static file). For this search it'll use the so called "finders" (as defined in the STATICFILES_FINDERS setting).
One of the default finders is the AppDirectoriesFinder, which will look in the "/static/" directory of each of the apps of yours INSTALLED_APPS setting.
Another default finder is the FileSystemFinder, which will look in directories you specify in the STATICFILES_DIRS setting.
BTW, both these search patterns are similar to how template loading works.
The same technique will be used when running the collectstatic command, except that it now will collect the files from the various locations (using the same finders as above), putting the found files into STATIC_ROOT, ready for deployment.
If you want just a solution - scroll down to the "Solution".
Overview
I was discovering the same problem yesterday. Here is what I found:
All you need is appropriate static finder, that will find your STATIC_ROOT and all its contents, but there is no such finder. Here are default finders:
django.contrib.staticfiles.finders.AppDirectoriesFinder - search installed django applications dirs for 'static' folder, but most of them use obsolete 'media' folders for now.
django.contrib.staticfiles.finders.FileSystemFinder - use all dirs mentioned in the STATICFILES_DIRS, but you can't add STATIC_ROOT into it.
django.contrib.staticfiles.finders.DefaultStorageFinder - search static in your DEFAULT_FILE_STORAGE which is django.core.files.storage.FileSystemStorage by default and it points to your MEDIA_ROOT
Solution
That's all, no additional choices. There are no choices to use STATIC_ROOT for now (in Django 1.3).
So I've just wrote my own custom finder for these needs:
My custom static finder file: finders.py:
from django.core.files.storage import FileSystemStorage
from django.contrib.staticfiles.finders import BaseStorageFinder
from django.conf import settings
class StaticFinder(BaseStorageFinder):
storage = FileSystemStorage(settings.STATIC_ROOT, settings.STATIC_URL)
settings.py:
STATICFILES_FINDERS = (
'finders.StaticFinder',
)
If you want to use it with another finders - I suggest to put them after it inside STATICFILES_FINDERS
And remember: this solution should be used only in development needs and never on production!
I found a quick and easy workaround to serve project global static files during development:
Start a new app that contains your projects static files (e.g. "manage.py startapp static_content")
Create a folder named 'static' in that app and put your static files there.
Add your new app to the list of installed apps
First of all, make sure that you have static serve enabled in your urls.py FOR DEVELOPMENT ONLY.
Also, you may have an extra slash in there. If your STATIC_URL == '/static/', then
{{ STATIC_URL }}/css/style.css should be {{ STATIC_URL }}css/style.css.
STATIC_ROOT = '/home/ws/be/bla/'
STATICFILES_DIRS = ('/home/ws/be/static/',)
STATIC_URL = '/static/'
This works for me. STATIC_ROOT must differ from STATICFILES_DIRS (Django version 1.4 pre-alpha SVN-16436)

Categories