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

后端 未结 2 1246
时光取名叫无心
时光取名叫无心 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 %}
            
            
        {% 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.

提交回复
热议问题