保存后,从Django表单获取模型ID [英] Getting the model ID from a Django form after having saved it
本文介绍了保存后,从Django表单获取模型ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
view.py
someForm = SomeForm(request.POST)
...
someForm .customSave(request.user)
forms.py
$ b $
def customSave(self,用户):
lv = self.save(commit = False)
lv.created_by = user
lv.save()
如何获取我刚刚从 someForm
保存的模型(或模型)? p>
解决方案
由于 ModelForm.save 是返回实例,您可能希望在您的customSave方法中返回实例
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $¬$ ()
return lv
那么你可以访问实例上的pk或id
inst = someForm.customSave(request.user)
inst.pk或inst.id
view.py
someForm = SomeForm(request.POST)
...
someForm.customSave(request.user)
forms.py
class SomeForm(ModelForm):
class Meta:
model = Some
def customSave(self,user):
lv = self.save(commit=False)
lv.created_by = user
lv.save()
How can I get the id of the model (or the model) I have just saved from someForm
?
解决方案
Since the behavior of ModelForm.save is to return the instance, you might want to return the instance in your customSave method
def customSave(self, user):
lv = self.save(commit=False)
lv.created_by = user
lv.save()
return lv
then you can access the pk or id on the instance
inst = someForm.customSave(request.user)
inst.pk or inst.id
这篇关于保存后,从Django表单获取模型ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文