简体   繁体   中英

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;

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM