[Answered ]-Django Static Setup

2πŸ‘

βœ…

  1. Put your static files into <app>/static or add an absolute path to STATICFILES_DIRS
  2. Configure your web server (you should not serve static files with Django) to serve files in STATIC_ROOT
  3. Point STATIC_URL to the base URL the web server serves
  4. Run ./manage.py collectstatic
  5. Be sure to use RequestContext in your render calls and {{ STATIC_URL }} to prefix paths
  6. Coffee and pat yourself on the back

A little bit more about running a web server in front of Django. Django is practically an application server. It has not been designed to be any good in serving static files. That is why it actively refuses to do that when DEBUG=False. Also, the Django development server should not be used for production. This means that there should be something in front of Django at all times. It may be a WSGI server such as gunicorn or a β€˜real’ web server such as nginx or Apache.

If you are running a reverse proxy (such as nginx or Apache) you can bind /static to a path in the filesystem and the rest of the traffic to pass through to Django. That means your STATIC_URL can be a relative path. Otherwise you will need to use an absolute URL.

πŸ‘€ferrix

0πŸ‘

The created project should have a static folder. Put all resources (images, …) in there.
Then, in your HTML template, you can reference STATIC_ROOT and add the resource path (relative to the static folder)

πŸ‘€MFARID

0πŸ‘

Here is the official documentation:

How to manage static files: https://docs.djangoproject.com/en/1.4/howto/static-files/

Static Files in general: https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/

If you are planning to to deploy in a production type setting then you should read the section here: https://docs.djangoproject.com/en/1.4/howto/static-files/#staticfiles-production

Generally you put our static and media folders outside of the django project app

πŸ‘€Jamie

0πŸ‘

  • Define your STATICFILES_DIRS, STATIC, and MEDIA path in the settings.
  • Create staticfiles folder beside your templates folder, urls.py, settings.py, etc…
  • You don’t have to create media folder because it will automatically created when you upload images.
  • In your urlconf put this one:

    from django.conf.urls import patterns, include, url
    from django.contrib import admin
    from django.conf import settings
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    from django.conf.urls.static import static
    
    admin.autodiscover()
    
    urlpatterns = patterns('',
        .............
    ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    urlpatterns += staticfiles_urlpatterns()
    
  • In templates:

    {% load static %}
    <img src="{% static 'images.png' %}">
    <img src="{{MEDIA_URL}}images.png">
    
πŸ‘€catherine

Leave a comment