我想保存modelForm,即使在POST上没有更改字段,因为我使用了一个jQuery函数来修改表格中的formset顺序,我想手动保存formset的位置。
如果没有更改字段,但是formset行是,则不会启动save()方法,并且不会保存位置。
形式:
class LayerMapOptions(models.Model):
layer = models.ForeignKey(Shapefile)
ezmap = models.ForeignKey(EzMap)
position = models.IntegerField(max_length=100)
visible = models.BooleanField()
视图:
def setMapOptions(request, map_name):
map_selected = EzMap.objects.get(map_name=map_name, created_by=request.user)
layers_ordered = LayerMapOptions.objects.filter(ezmap=map_selected).order_by('position')
layerForm = modelformset_factory(LayerMapOptions, form=LayerMapOptionsForm, extra=0, can_delete=True)
if request.POST:
formset = layerForm(request.POST, queryset=layers_ordered)
pk_list = request.POST.get("layersOrder")
if formset.is_valid():
instances = formset.save(commit=False)
for instance in instances2:
instance.position = pk_list.index(instance.layer.pk)
instance.save()
save_link = u"/ezmapping/map/%s" % (map_name)
return HttpResponseRedirect(save_link)
else:
formset = layerForm(queryset=layers_ordered)
return render_to_response("ezmapping/manage_map_Options.html", {'formset': formset}, context_instance=RequestContext(request))
形式:
class LayerMapOptionsForm(ModelForm):
def __init__(self, *args, **kwargs):
super(LayerMapOptionsForm, self).__init__(*args, **kwargs)
self.fields['position'].widget = forms.HiddenInput()
class Meta:
model = LayerMapOptions
fields = ['layer', 'visible', 'position']
可以看到,当调用instances = formset.save(commit=False)
时,只有已经修改的formets被放入instances
。我想将所有formset实例化,并单独更新。
答案 0 :(得分:4)
如果模型的数据没有被更改,模型没有标记为脏,所以我假设formset.save(commit = False)返回Null。但是你知道数据很脏,所以为什么不这样做呢:
if formset.is_valid():
for form in formset:
instance = form.instance
instance.position = pk_list.index(instance.layer.pk)
instance.save()
换句话说,您只需从每个绑定表单中获取模型实例,您不依赖于save方法来回答它们。
答案 1 :(得分:3)
还有另外一种方法,如何:
class LayerMapOptionsForm(forms.ModelForm):
def has_changed(self, *args, **kwargs):
return True