使模型中的用户默认为当前用户
我有以下问题:
from django.contrib.auth.models import User
class ClientDetails(models.Model):
created_by = models.ForeignKey(User)
...
如何将 created_by
默认为当前登录的用户?
(我想这样做,主要是因为我可以将其隐藏在管理视图中,但也因为当我保存实例时,我不想每次都填充它)
I have the following:
from django.contrib.auth.models import User
class ClientDetails(models.Model):
created_by = models.ForeignKey(User)
...
How do I make created_by
default to the currently logged in user?
(I want to do this so I can hide it in the admin view mainly but also because when I save an instance I don't want to be filling it every time)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于您需要从
request
对象获取当前登录的用户,因此您无法在模型的save
方法中获取它,但您可以覆盖模型管理员的save_model
-方法:Since you need to get the currently logged in user from a
request
object you cannot get it in the model'ssave
-method,but you can eg override the model admin'ssave_model
-method:您必须重写
admin.py
中模型 Admin 类中的get_changeform_initial_data
方法,如下所示:通过这种方式,您可以获得自
created_by
以来最优雅的解决方案> 当您创建新记录时,字段会被归档。You have to override
get_changeform_initial_data
method in your model Admin class inadmin.py
as follows:In such way you obtain the most elegant solution since the
created_by
field is filed up when you create new record.我最近遇到了类似的问题,这是来自我的views.py文件
然后我有一个“圆圈”模型的表单,它实际上只是一个包装器(forms.py)
记住在您的视图中导入表单!
编辑:甚至不确定您是否需要单独的表单,关键位是假提交,其次是真正的提交
I had a similar issue recently, this is from my views.py file
And then I had a form for the 'circles' model, which was just a wrapper really (forms.py)
Remember to import the form in your view!
Edit: not even sure if you even need to bother with the separate form, the key bit is the fake commit, followed by the real
基于已接受的答案,如果您希望使用基于类的视图执行此操作,您可以按照 docs,覆盖类视图上的
form_valid()
方法:Building on the accepted answer, if you're looking to do this with Class Based views, you can follow the instructions in the docs, overriding the
form_valid()
method on the class view:普通模型字段有一个默认参数。但据我所知,ForeignKeys 没有,所以我想你需要使用 post_save 信号。
Normal modelfields have a default argument. But ForeignKeys do not as far as I know, so I guess you need to work with a post_save signal.
我发现:
来自 这里。但有没有更简单的方法呢?
I found:
from here. But isn't there an easier way?