Django - static files serving javascript, css and image files

I need static server files in my Django project.

I would like to place them in the / static directory and be able to refer to them in my templates.

I read "Managing Static Files" in the documentation, and I'm confused. I followed the instructions, but could not get it to work.

1) I put my static files in / static in every application in my project.

2) django.contrib.staticfiles is included in my INSTALLED_APPS.

I set the following options in the 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 lift the page and look at the source, the line:

 <script type="text/javascript" src=/a_ajax.js></script> 

Nothing seems to have been passed to the template.

What am I doing wrong?

+7
source share
3 answers

Given that you are using Django 1.4 or higher, here is my explanation:

In Django 1.3, static files were separated from uploaded files (media), and now they have their own home.

To serve static files (css, js, images, etc.) in the required development environment:

  • Put these files in the appropriate static subdirectory application
  • Make sure you have django.contrib.staticfiles.finders.AppDirectoriesFinder in settings.py (this is the default behavior)

Directory structure will be:

 __| project_root/ ____| your_app/ ______| static/ ________| test.css ________| some.js 

Thus, a request to http://localhost:8000/static/test.css will be redirected to your_app/static/test.css .

Note that you do not need to change the STATIC_ROOT parameter until you go into the production environment in which you will need to run ./manage.py collectstatic .

The collectstatic command will collect files from subdirectories of the static application and place them all in a unique place (the directory defined in STATIC_ROOT )

If you intend to deploy your project in production, see the ./manage.py collectstatic documentation .

+9
source

The 'django.core.context_processors.static' is located in TEMPLATE_CONTEXT_PROCESSORS var in settings.py .

see documentation: Accessing 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 ) 
+2
source

In newer versions of Django, I attach to static files in the html template like this:

<script type="text/javascript" src="{% static 'admin/js/labeler.js' %}"> </script>

The Django docs on STATIC are here: https://docs.djangoproject.com/en/1.9/howto/static-files/

+1
source

All Articles