How to do it...

Follow these steps to create and include the JavaScript settings:

  1. In the views.py of your utils app, create the render_js() view that returns a response of the JavaScript content type, as shown in the following code:
# utils/views.py
from datetime import datetime, timedelta, timezone
from email.utils import format_datetime

from django.shortcuts import render
from django.views.decorators.cache import cache_control


@cache_control(public=True)
def render_js(request, template_name, cache=True, *args, **kwargs):
response = render(request, template_name, *args, **kwargs)
response["Content-Type"] =
"application/javascript; charset=UTF-8"
if cache:
now = datetime.now(timezone.utc)
response["Last-Modified"] = format_datetime(now,
usegmt=True)

# cache in the browser for 1 month
expires = now + timedelta(days=31)
response["Expires"] = format_datetime(expires,
usegmt=True)
else:
response["Pragma"] = "No-Cache"
return response
  1. Create a settings.js template that returns JavaScript under the global project_settings variable, as follows:
# templates/settings.js
{% load static %}
{% get_media_prefix as MEDIA_URL %}
{% get_static_prefix as STATIC_URL %}
window.project_settings = {
MEDIA_URL: '{{ MEDIA_URL|escapejs }}',
STATIC_URL: '{{ STATIC_URL|escapejs }}',
lang: '{{ LANGUAGE_CODE|escapejs }}',
languages: { {% for lang_code, lang_name in LANGUAGES %}
'{{ lang_code|escapejs }}': '{{ lang_name|escapejs }}'{% if not forloop.last %},{% endif %}
{% endfor %} }
};
  1. Create a URL rule to call a view that renders JavaScript settings, as follows:
# myproject/urls.py
from django.conf.urls.i18n import i18n_patterns
from django.urls import path

urlpatterns = [
# ...
]

urlpatterns += i18n_patterns(
path("js-settings/", "utils.views.render_js",
{"template_name": "settings.js"},
name="js_settings"),
)
  1. Finally, if you haven't done so yet, create a base template as described in the Arranging the base.html template recipe. Include the rendered JavaScript settings file in the base_js block in that template, as shown in the following code:
{# templates/base.html #}
{% block base_js %}
{# ... #}
<script src="{% url "js_settings" %}"></script>
{% endblock %}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.196.184