Skip to content Skip to sidebar Skip to footer

Django : How To Access Current Logged In User's Id In Javascript?

I have defined a get_queryset method in a viewset. class BooksViewSet(ReadOnlyModelViewSet): serializer_class = BooksSerializer permission_classes = (IsAuthorizedToAccess,

Solution 1:

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);

Solution 2:

You can use template tag as well. Like {{author.id}} You can also assign to a javascript variable the value and then use it

var id = {{ author.id }}

Solution 3:

If the javascript is in your template file, you can access it like any other like this:

{% for author in authors %}
    if('{{author.id}}' == "current user id")
    {
    }

{% endfor %}

Post a Comment for "Django : How To Access Current Logged In User's Id In Javascript?"