在Django ModelForm中重写save方法

75 投票
1 回答
93209 浏览
提问于 2025-04-15 11:22

我在重写一个 ModelForm 的保存方法时遇到了麻烦。以下是我收到的错误信息:

Exception Type:     TypeError  
Exception Value:    save() got an unexpected keyword argument 'commit'

我想要做的是让一个表单提交多个值到三个字段,然后为这些字段的每种组合创建一个对象,并保存每一个对象。如果能给我一些有用的提示,那就太好了。

文件 models.py

class CallResultType(models.Model):
    id = models.AutoField(db_column='icontact_result_code_type_id', primary_key=True)
    callResult = models.ForeignKey('CallResult', db_column='icontact_result_code_id')
    campaign = models.ForeignKey('Campaign', db_column='icampaign_id')
    callType = models.ForeignKey('CallType', db_column='icall_type_id')
    agent = models.BooleanField(db_column='bagent', default=True)
    teamLeader = models.BooleanField(db_column='bTeamLeader', default=True)
    active = models.BooleanField(db_column='bactive', default=True)

文件 forms.py

from django.forms import ModelForm, ModelMultipleChoiceField
from callresults.models import *

class CallResultTypeForm(ModelForm):
    callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all())
    campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all())
    callType = ModelMultipleChoiceField(queryset=CallType.objects.all())

    def save(self, force_insert=False, force_update=False):
        for cr in self.callResult:
            for c in self.campain:
                for ct in self.callType:
                    m = CallResultType(self) # this line is probably wrong
                    m.callResult = cr
                    m.campaign = c
                    m.calltype = ct
                    m.save()

    class Meta:
        model = CallResultType

文件 admin.py

class CallResultTypeAdmin(admin.ModelAdmin):
    form = CallResultTypeForm

1 个回答

169

在你的 save 方法中,必须有一个参数叫 commit。如果有什么东西要覆盖你的表单,或者想要修改你要保存的内容,它会使用 save(commit=False),然后修改输出,最后自己保存。

另外,你的 ModelForm 应该返回它正在保存的模型。通常,一个 ModelForm 的 save 方法看起来会像这样:

def save(self, commit=True):
    m = super(CallResultTypeForm, self).save(commit=False)
    # do custom stuff
    if commit:
        m.save()
    return m

可以了解一下 这个 save 方法

最后,你的很多 ModelForm 的功能可能因为你访问数据的方式不对而无法正常工作。你需要用 self.fields['callResult'],而不是 self.callResult

更新: 针对你的回答:

顺便说一下:为什么不直接在模型中使用 ManyToManyField 呢?这样你就不用做这些事情了。看起来你在存储重复的数据,还给自己(和我 :P)增加了工作量。

from django.db.models import AutoField  
def copy_model_instance(obj):  
    """
    Create a copy of a model instance. 
    M2M relationships are currently not handled, i.e. they are not copied. (Fortunately, you don't have any in this case)
    See also Django #4027. From http://blog.elsdoerfer.name/2008/09/09/making-a-copy-of-a-model-instance/
    """  
    initial = dict([(f.name, getattr(obj, f.name)) for f in obj._meta.fields if not isinstance(f, AutoField) and not f in obj._meta.parents.values()])  
    return obj.__class__(**initial)  

class CallResultTypeForm(ModelForm):
    callResult = ModelMultipleChoiceField(queryset=CallResult.objects.all())
    campaign = ModelMultipleChoiceField(queryset=Campaign.objects.all())
    callType = ModelMultipleChoiceField(queryset=CallType.objects.all())

    def save(self, commit=True, *args, **kwargs):
        m = super(CallResultTypeForm, self).save(commit=False, *args, **kwargs)
        results = []
        for cr in self.callResult:
            for c in self.campain:
                for ct in self.callType:
                    m_new = copy_model_instance(m)
                    m_new.callResult = cr
                    m_new.campaign = c
                    m_new.calltype = ct
                    if commit:
                        m_new.save()
                    results.append(m_new)
         return results

这允许 CallResultTypeForm 进行继承,以防将来需要。

撰写回答