[英]Django : How to access current logged in user's id in javascript?
I have defined a get_queryset method in a viewset.我在视图集中定义了一个 get_queryset 方法。
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.使用 javascript 我想在一侧显示当前用户的书籍,在右侧显示其他所有用户的书籍。 I did all the code but could not access the current user id in my js file.
我完成了所有代码,但无法访问我的 js 文件中的当前用户 ID。
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.
对于我所做的所有搜索,我知道如何将此用户 ID 添加为隐藏字段或传递此 ID。但我不能,因为该方法只允许返回查询集对象。
Can anyone please help me understand this.谁能帮我理解这一点。
EDIT: MY SOLUTION编辑:我的解决方案
In my views, i define the get_context_data method.在我看来,我定义了 get_context_data 方法。
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:在我的 JS 中:
var x= document.getElementById("author_id").value; 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.从 Django 2.1 开始,专门针对此用例引入了一个新的内置模板标签:json_script。
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#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.新标签将安全地序列化模板值并防止 XSS。
It is not necessary to set any context variables as the request.user is already included in every view:没有必要设置任何上下文变量,因为 request.user 已经包含在每个视图中:
template.html模板.html
{{ request.user.id|json_script:"user_id" }}
script.js脚本.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
像 {{author.id}} 您也可以将值分配给 javascript 变量然后使用它
var id = {{ author.id }}
If the javascript is in your template file, you can access it like any other like this:如果 javascript 在您的模板文件中,您可以像访问其他文件一样访问它:
{% for author in authors %}
if('{{author.id}}' == "current user id")
{
}
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.