Django : How to access current logged in user's id in javascript?

As of Django 2.1, a new built in template tag has been introduced specifically for this use case: json_script.

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#json-script

The new tag will safely serialize template values and protects against XSS.

It is not necessary to set any context variables as the request.user is already included in every view:

template.html

{{ request.user.id|json_script:"user_id" }}

script.js

const user_id = JSON.parse(document.getElementById('user_id').textContent);