I need to server static files in my Django project.
I would like to place them in /static directory and be able to reference them in my templates.
I've been reading "Managing static files" in the documentation and I am confused. I've followed the instructions but am not able to get it to work.
1) I have put my static files in /static under each app in my project.
2) django.contrib.staticfiles is included under my INSTALLED_APPS.
I've set the following variables in settings:
STATIC_ROOT = '/static/'
STATIC_URL = '/static/'
In my template I have the following line:
<script type="text/javascript" src={{ STATIC_URL }}/a_ajax.js></script>
however when I bring up the page and look at source the line is:
<script type="text/javascript" src=/a_ajax.js></script>
It seems like nothing was passed to the template.
What am I doing wrong?
Considering that you are using Django 1.4 or higher, here is my explanation:
In Django 1.3 the static files were separated from the uploaded files (media) and now, they have their own home.
To serve static files (css, js, images, etc) in the development environment you need:
static
subdirectorydjango.contrib.staticfiles.finders.AppDirectoriesFinder
in your settings.py
(this is the default behavior)The directory structure will be:
__| project_root/
____| your_app/
______| static/
________| test.css
________| some.js
So the request to http://localhost:8000/static/test.css
will be routed to your_app/static/test.css
.
Note that you don't need to change STATIC_ROOT
setting, until you go to production environment that you will need to run ./manage.py collectstatic
.
The collectstatic
command will collect files from the app's static
subdirectories and put them all in an unique place (the directory defined in STATIC_ROOT
)
If you are going to deploy your project in production, see ./manage.py collectstatic documentation.
Include 'django.core.context_processors.static'
is in your TEMPLATE_CONTEXT_PROCESSORS
var in settings.py
.
see documentation: Referring to static files in templates
And in the view, use the RequestContext
object instead of the Context
object.
def view1(request):
...
context = RequestContext(...
return render_to_response( ... , context )
In newer versions of Django, this is how I link to static files in a html template:
<script type="text/javascript" src="{% static 'admin/js/labeler.js' %}"> </script>
Django docs on STATIC are here: https://docs.djangoproject.com/en/1.9/howto/static-files/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With