About Access to Essential Settings in JavaScript

In the base.html template, you can create a JavaScript dictionary with the essential settings, so that you can access them in all your JavaScript files:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{% get_available_languages as LANGUAGES %}
<script>
window.settings = {
    DEBUG: {{ debug|yesno:"true,false" }},
    MEDIA_URL: '{{ MEDIA_URL }}',
    STATIC_URL: '{{ STATIC_URL }}',
    LANGUAGE_CODE: '{{ request.LANGUAGE_CODE }}',
    LANGUAGES: [{% for lang_code, lang_name in LANGUAGES %}
        '{{ lang_code }}'{% if not forloop.last %}, {% endif %}
    {% endfor %}],
};
</script>

Tips and Tricks Programming Django 4.2 Django 3.2 Django 2.2 JavaScript