Django:如何在javascript中访问当前登录的用户ID? [英] Django : How to access current logged in user's id in javascript?

查看:72
本文介绍了Django:如何在javascript中访问当前登录的用户ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在视图集中定义了一个get_queryset方法。

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

使用JavaScript我要在一侧显示当前用户的书籍和书籍右边的所有其他用户。
我做了所有代码,但无法访问我的js文件中的当前用户ID。

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")
{
}

我要像这样访问用户ID。
我所做的所有搜索,我都知道有关将此用户ID添加为隐藏字段或传递此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.

编辑:我的解决方案

在我看来,我定义了get_context_data方法。

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;

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

推荐答案

您也可以使用模板标记。像{{author.id}}
一样,您也可以将值赋给javascript变量然后使用它

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

这篇关于Django:如何在javascript中访问当前登录的用户ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆