Getting the model ID from a Django form after having saved it
view.py
1 2 3 | someForm = SomeForm(request.POST) ... someForm.customSave(request.user) |
forms.py
1 2 3 4 5 6 7 8 9 | class SomeForm(ModelForm): class Meta: model = Some def customSave(self,user): lv = self.save(commit=False) lv.created_by = user lv.save() |
如何获取我刚刚从
由于 ModelForm.save 的行为是返回实例,您可能希望在 customSave 方法中返回实例
1 2 3 4 5 | def customSave(self, user): lv = self.save(commit=False) lv.created_by = user lv.save() return lv |
然后你可以访问实例上的pk或id
1 2 | inst = someForm.customSave(request.user) inst.pk or inst.id |
在调用
在您的模型类中覆盖保存方法:
1 2 3 | def save(self, form, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) logger.debug(self.id) |