Django:保存模型时填充用户ID [英] Django: Populate user ID when saving a model
问题描述
我有一个model_by字段的模型链接到标准的Django用户模型。当保存模型时,我需要自动填充当前用户的ID。我无法在管理层执行此操作,因为网站的大部分内容不会使用内置的管理员。任何人都可以建议我应该怎么做?
I have a model with a created_by field that is linked to the standard Django User model. I need to automatically populate this with the ID of the current User when the model is saved. I can't do this at the Admin layer, as most parts of the site will not use the built-in Admin. Can anyone advise on how I should go about this?
推荐答案
如果你想要一些在管理员和其他地方都可以工作的东西,您应该使用自定义模型。基本思想是覆盖 __ init __
方法来获取一个额外的参数 - 请求,并将其存储为表单的属性,然后也覆盖保存方法来设置用户id保存到数据库中。
If you want something that will work both in the admin and elsewhere, you should use a custom modelform. The basic idea is to override the __init__
method to take an extra parameter - request - and store it as an attribute of the form, then also override the save method to set the user id before saving to the database.
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(MyModelForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(MyModelForm, self).save(*args, **kwargs)
if self.request:
obj.user = self.request.user
obj.save()
return obj
这篇关于Django:保存模型时填充用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!