Django: How to access current user id in javascript?

I defined the get_queryset method in the view.

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 the books of the current user on one side and the books of other users on the right side. I did all the code but could not access the current user id in the js file.

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

I want to access the user id. For all the searches that I did, I found out about adding this user id as a hidden field or passing this id. But I can not, because the method only allows you to return the queryset object.

Can anyone help me figure this out.

EDIT: MY DECISION

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}}>

JS:

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

+4
2

. {{author.id}} javascript ,

var id = {{ author.id }}
+1

javascript , , :

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

{% endfor %}
0

Source: https://habr.com/ru/post/1623738/


All Articles