如何将当前登录的用户分配为模型字段的默认值? [英] How to assign currently logged in user as default value for a model field?

查看:204
本文介绍了如何将当前登录的用户分配为模型字段的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

  class Task(models.Model):
。 ..
created_by = models.ForeignKey(User,** default = [LoggedInUser] ** blank = True,null = True,related_name ='created_by')
pre>

这可能吗?我找不到什么是正确的方式来获取登录的用户,除了请求。用户,在一个视图,这似乎不起作用。



PS_我意识到我可以用其他方式初始化模型数据,但我认为这是最干净的方式。

解决方案

你不能这样做。 Django(和Python)的全局值几乎都是零,这是一个好事(tm)。通常,您可以在视图(请求)中使用 request.user 获取当前用户。然后,您可以将其作为参数传递给各种方法/函数,但尝试设置全局用户将仅导致多线程环境中的眼泪。



应该有一个保险杠贴纸,说全球是邪恶的。这将让您对PHP的第一个问题有一个好主意。


I'd like to do something like this:

class Task(models.Model):
    ...
    created_by = models.ForeignKey(User, **default=[LoggedInUser]** blank=True, null=True, related_name='created_by')

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_ I realise I could initialize the Model data by other means, but I think this is the cleanest way.

解决方案

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.

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屋!

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