[英]Django admin: Get logged In users id in django
I am new to django and learnign it. 我是django的新手,正在学习它。 I am using django's Auth and i need to get the id of the logged in user at some place.
我正在使用django的Auth,我需要在某个地方获取登录用户的ID。 I have tried :
我努力了 :
HttpRequest.user.id
referring to the Django docs but this throws exception : HttpRequest.user.id
引用Django文档,但这会引发异常:
Exception Type: AttributeError
Exception Value: type object 'HttpRequest' has no attribute 'user'
My code : 我的代码:
from django.http import HttpRequest
#...some other code here..#
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField('post body')
author = models.ForeignKey(User)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
self.author = HttpRequest.user.id
super(Post, self).save(force_insert, force_update, using, update_fields)
--UPDATE --- -更新-
I have also tried : 我也尝试过:
from django.http import request
and then in save method : 然后在保存方法中:
self.author = request.user.id
but it gives me exception - 但这给了我例外-
Exception Type: AttributeError
Exception Value: 'module' object has no attribute 'user'
You shouldn't override the model's save()
method, but override the admin save_model()
method instead: 您不应覆盖模型的
save()
方法,而应覆盖admin save_model()
方法:
class Post(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.user = request.user
super(Post, self).save_model(request, obj, form, change)
HttpRequest is a class , which doesn't have an user
attribute. HttpRequest是一个类 ,没有
user
属性。 You need to obtain the request object , most likely from a view function. 您需要获取请求对象 ,最有可能从视图函数中获取。 Then you can pass the user object, or its id to your model
save()
method: 然后,您可以将用户对象或其ID传递给模型的
save()
方法:
def view_function(request):
user = request.user
# Get the object you want to save the user field to
post = Post.objects.get(...)
post.user = user
# Or post.user_id = user.id
post.save()
... ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.