[Django]-How can I get the MEDIA_URL from within a Django template?

6👍

To access STATIC_URL in your templates, make sure django.core.context_processors.static is in TEMPLATE_CONTEXT_PROCESSORS, and that you’re using a RequestContext. More details here.

In addition, static files should be placed under STATIC_URL, not MEDIA_URL, unless it is user-uploaded content.

1👍

I would say that you dont have to use MEDIA_URL and MEDIA_ROOT for your Js,css,img files!

I use STATIC_ROOT,STATIC_URL instead! as far as I know MEDIA_* is for upload of files, such as images, or any document!

Also I use STATIC_* because in my case, I have my js,css,… files in a S3 storage! so when I run collectstatic it just copy all my STATIC files to my cloud storage! So in my templates I have something like this:

    {% block js %}
        <script src="{{ STATIC_URL }}js/libs/modernizr-2.0.min.js"></script>
        <script src="{{ STATIC_URL }}js/libs/respond.min.js"></script>
    {% endblock %}

Check it out this note from Django docs:

Note In previous versions of Django, it was common to place static
assets in MEDIA_ROOT along with user-uploaded files, and serve them
both at MEDIA_URL. Part of the purpose of introducing the staticfiles
app is to make it easier to keep static files separate from
user-uploaded files.

For this reason, you need to make your MEDIA_ROOT and MEDIA_URL
different from your STATIC_ROOT and STATIC_URL. You will need to
arrange for serving of files in MEDIA_ROOT yourself; staticfiles does
not deal with user-uploaded files at all. You can, however, use
django.views.static.serve() view for serving MEDIA_ROOT in
development; see Serving other directories.

Leave a comment