覆盖Django ModelForm中的save方法

Jos*_*ton 60 python django django-forms django-admin

我无法覆盖ModelForm保存方法.这是我收到的错误:

Exception Type:     TypeError  
Exception Value:    save() got an unexpected keyword argument 'commit'
Run Code Online (Sandbox Code Playgroud)

我的目的是让表单为3个字段提交许多值,然后为这些字段的每个组合创建一个对象,并保存每个对象.在正确的方向上有用的推动将是王牌.

文件 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)
Run Code Online (Sandbox Code Playgroud)

文件 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
Run Code Online (Sandbox Code Playgroud)

文件 admin.py

class CallResultTypeAdmin(admin.ModelAdmin):
    form = CallResultTypeForm
Run Code Online (Sandbox Code Playgroud)

tgh*_*ghw 142

在你的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
Run Code Online (Sandbox Code Playgroud)

阅读上save方法.

最后,很多这个ModelForm只是因为你访问事物的方式而无法工作.而不是self.callResult,你需要使用self.fields['callResult'].

更新:回答你的回答:

旁白:为什么不在ManyToManyField模型中使用s,这样你就不必这样做了?好像你正在存储冗余数据并为自己(和我: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
Run Code Online (Sandbox Code Playgroud)

这允许继承CallResultTypeForm,以防万一必要.

  • 对于现在(目前是 Django 1.10)的任何人,[`ModelClass.save()` 方法](https://github.com/django/django/blob/master/django/forms/models.py#L438)现在只有 `commit=True` 参数——它没有 `force_insert` 或 `force_update` 参数。 (2认同)