Here is the code in my base.html header
<script> var auth_status = "{{ user.is_authenticated }}" </script> {% block scripts %} {% endblock %}
The rest of the scripts in my site are in the block scripts.
In a child template (within the script block and within script tags) I have this code,
if (auth_status) { //something }
The error at hand is auth_status is always True, when it should be on and off depending on if the user is logged in. Request_context is being passed to the template so that should not be the error.
Thanks
As of Django 2.1, a new built in template tag has been introduced specifically for this use case: json_script . The new tag will safely serialize template values and protects against XSS. Django docs excerpt: Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript.
While most of Django core is Python, the admin and gis contrib apps contain JavaScript code. Please follow these coding standards when writing JavaScript code for inclusion in Django.
In JavaScript, a boolean value is one that can either be TRUE or FALSE. If you need to know “yes” or “no” about something, then you would want to use the boolean function. It sounds extremely simple, but booleans are used all the time in JavaScript programming, and they are extremely useful.
Boolean is a datatype that returns either of two values i.e. true or false. In JavaScript, Boolean is used as a function to get the value of a variable, object, conditions, expressions, etc. in terms of true or false.
For what I see your auth_status
variable seems to be a string, not a boolean. A variable with a non-empty string on javascript will evaluate to true
on an if
clause.
Anyhow, something like
<script> var auth_status = {{ user.is_authenticated }}; </script>
will not work because that will generate this HTML:
<script> var auth_status = True; </script>
As Python's True boolean is uppercased.
This should do the translation from Python to Javascript:
<script> var auth_status = {{ user.is_authenticated|yesno:"true,false" }}; </script>
Check yesno docs here: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#yesno
Another option would be to use the jinja2 tojson
filter:
<script> let javascript_var = {{ python_var|tojson }}; </script>
You may also want to use the safe
filter depending on what you're passing:
<script> let javascript_var = {{ python_var|tojson|safe }}; </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With