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

后端 未结 2 1220
时光取名叫无心
时光取名叫无心 2021-01-21 03:38

I\'m somewhat confused as to how Django operates with static content. Essentially, in the settings.py file, we define MEDIA_URL which points to the URL

相关标签:
2条回答
  • 2021-01-21 04:14

    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.

    0 讨论(0)
  • 2021-01-21 04:22

    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.

    0 讨论(0)
提交回复
热议问题