Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    def get_queryset(self):
        queryset = Books.objects.all();
        return queryset

Using javascript i want to display books of current user on one side and books of other all users on right side. I did all the code but could not access the current user id in my js file.

if(auther.id == "current user id")
{
}

I Want to access the user id like this. For all search i did , i got to know about adding this user id as a hidden field or passing this id .But i cant as the method only allows to return the queryset object.

Can anyone please help me understand this.

EDIT:MY SOLUTION

In my views , i define the get_context_data method.

 def get_context_data(self, *args, **kwargs):
    ctx = super(class_name, self).get_context_data(*args, **kwargs)
    ctx["author_id"]=self.request.user.id
    return ctx

In my template,i defined a hidden field:

<input type="hidden" id="userId" value={{author_id}}>

And in my JS:

var x= document.getElementById("author_id").value;

like image 889
siddaqui Avatar asked Jan 11 '16 10:01

siddaqui


2 Answers

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);
like image 176
ChrisRob Avatar answered Oct 02 '22 03:10

ChrisRob


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 }}
like image 22
Stefano Avatar answered Oct 02 '22 03:10

Stefano