Reputation: 7635
I want to save the modelForm even if no field are changed on POST because I use a jQuery function that modify the order of formsets in a table, and I want to save the position of the formset manually.
When no field are changed, but that the formset rows is, the save() method is not launched, and the position is not saved.
form:
class LayerMapOptions(models.Model):
layer = models.ForeignKey(Shapefile)
ezmap = models.ForeignKey(EzMap)
position = models.IntegerField(max_length=100)
visible = models.BooleanField()
view:
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))
form:
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']
One could see that when instances = formset.save(commit=False)
is called, only formets that had been modified are put into instances
. I would like to put into instance all formset, and update all individually.
Upvotes: 3
Views: 2259
Reputation: 927
There is another way, how to to this:
class LayerMapOptionsForm(forms.ModelForm):
def has_changed(self, *args, **kwargs):
return True
Upvotes: 7
Reputation: 2405
If the data for the models hasn't been altered, the model isn't marked as dirty, so I'm presuming the formset.save(commit=False) returns Null. But you know the data is dirty, so why not just do this:
if formset.is_valid():
for form in formset:
instance = form.instance
instance.position = pk_list.index(instance.layer.pk)
instance.save()
In other words, you just obtain the model instance from each bound form, you don't rely on the save method to answer them.
Upvotes: 5