如果模型具有w,x,y,z属性,并且基于此模型的模型形式仅包含w和x的字段,那么如何仅为模型形式连接post_save_receiver(或类似的)?
我希望接收者忽略{y}和z save()
s。并且只有在更新特定表单或特定字段时才执行post_save函数中的代码。
以下代码应根据保存的字段或已保存的模型执行:
def profile_post_save_receiver(sender, instance, created, *args, **kwargs):
...
post_save.connect(profile_post_save_receiver, sender=Profile)
这是两个独立的模型。 post_save
代码只应在PreferenceUpdateForm
更新时发生,并忽略对ProfileUpdateForm
的更改:
from .models import Profile
from django import forms
class PreferenceUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = [
"preference1",
"preference2",
]
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = [
"bio",
"profile_image",
]
如果这不是理想的解决方法,我还能取得类似的结果吗?
答案 0 :(得分:1)
信号不是正确的方法,特别是如果您自己编写模型表单。只需覆盖表单的save()
方法即可执行您需要的任何操作。像这样:
class ProfileUpdateForm(forms.ModelForm):
def save(self, commit=True):
# Call parent save() method
instance = super(ProfileUpdateForm, self).save(commit)
# Now you can do whatever work you need to with the instance
# that has just been saved.