如何将当前登录的用户指定为模型字段的默认值? [英] How to assign currently logged in user as default value for a model field?
问题描述
我想做这样的事情:
class Task(models.Model):
...
created_by = models.ForeignKey(User, **default=[LoggedInUser]** blank=True, null=True, related_name='created_by')
这可能吗?除了在视图中执行 request.user 之外,我找不到获取登录用户的正确方法,这似乎在这里不起作用.
Is this possible? I couldn't find what's the proper way to get the logged in user, apart from doing request.user, in a view, which doesn't seem to work here.
PS_我意识到我可以通过其他方式初始化模型数据,但我认为这是最干净的方法.
PS_ I realise I could initialize the Model data by other means, but I think this is the cleanest way.
推荐答案
不,你不能这样做.Django(和 Python)几乎零 全局值,这是一件好事(tm).通常,您可以使用 request.user
在 view(request)
中获取当前用户.然后,您可以将其作为参数传递给各种方法/函数,但尝试设置全局 user
只会导致多线程环境中的眼泪.
No, you can't do it this way. Django (and Python) has pretty much zero global values, and that's a Good Thing(tm). Normally you get the current user in the view(request)
with request.user
. You can then pass that as a param to various methods/functions, but trying to set a global user
will only lead to tears in a multi-threaded environment.
应该有一个保险杠贴纸,上面写着,Globals are Evil.这会让您对我的 PHP 第一个问题有一个很好的了解.
There should be a bumper sticker that says, Globals are Evil. This will give you a good idea about my Number One problem with PHP.
这篇关于如何将当前登录的用户指定为模型字段的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!