重写ModelForm
保存方法时遇到问题。这是我收到的错误:
Exception Type: TypeError
Exception Value: save() got an unexpected keyword argument 'commit'
我的目的是让一个表单为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)
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
在
save
中,必须有参数commit
。如果有任何内容覆盖您的表单,或者想要修改它保存的内容,它将执行save(commit=False)
,修改输出,然后保存它本身。此外,您的ModelForm应该返回它正在保存的模型。通常模型的
save
看起来像:阅读the ^{} method 。
最后,很多这种模型表单不会仅仅因为您访问事物的方式而工作。您需要使用
self.fields['callResult']
,而不是self.callResult
。更新:针对您的回答:
旁白:为什么不在模型中使用
ManyToManyField
s,这样就不必这样做了?似乎你在存储冗余数据,为自己(和我)做更多的工作。这允许继承
CallResultTypeForm
,以防万一。相关问题 更多 >
编程相关推荐