Django : How to access current logged in user'

2019-05-04 09:43发布

问题:

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;

回答1:

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


回答2:

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