即使在 POST 上没有更改任何字段,我也想保存 modelForm,因为我使用了一个 jQuery 函数来修改表格中表单集的顺序,并且我想手动保存表单集的位置。
如果没有更改任何字段,但 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)
被调用时,只有被修改过的格式才会被放入instances
. 我想将所有表单集放入实例中,并单独更新所有内容。