Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Static files serving javascript , css and image files

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?

like image 712
afshin Avatar asked Jun 10 '11 00:06

afshin


3 Answers

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:

  1. Put these files in their respective app's static subdirectory
  2. Make sure you have django.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.

like image 150
caio Avatar answered Oct 07 '22 12:10

caio


Include 'django.core.context_processors.static' is in your TEMPLATE_CONTEXT_PROCESSORS var in settings.py.

see documentation: Referring to static files in templates

Update:

And in the view, use the RequestContext object instead of the Context object.

def view1(request):
    ...
    context = RequestContext(...
    return render_to_response( ... , context )
like image 28
manji Avatar answered Oct 07 '22 13:10

manji


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/

like image 1
Mikeumus Avatar answered Oct 07 '22 13:10

Mikeumus