Override Django inlineformset_factory has_changed() to always return True
I am using the django inlineformset_factory function.
a = get_object_or_404(ModelA, pk=id)
FormSet = inlineformset_factory(ModelA, ModelB)
if request.method == 'POST':
metaform = FormSet (instance=a, data=request.POST)
if metaform.is_valid():
f = metaform.save(commit=False)
for instance in f:
instance.updated_by = request.user
instance.save开发者_运维百科()
else:
metaform = FormSet(instance=a)
return render_to_response('nodes/form.html', {'form':metaform})
What is happening is that if I change any of the data then everything works ok and all the data gets updated. However if I don't change any of the data then the data is not updated. i.e. only entries which are changed go through the for loop to be saved. I guess this makes sense as there is no point saving data if it has not changed. However I need to go through and save every object in the form regardless of whether it has any changes on not.
So my question is how do I override this so that it goes through and saves every record whether it has any changes or not?
Hope this makes sense
Thanks
inlineformset_factory can, I think, take a form object. What I believe you could do is create a forms.ModelForm, then add a field like
always_update = forms.IntegerField(required=False)
and then in the __init__
function do something like self.fields['always_update'].initial = int(time.time())
. I believe this will force it to update, but you'll have to test this.
If the updated_by
field is always going to be the same for every ModelB instance related to a particular ModelA instance, shouldn't you just store it once on the parent rather than on every child?
精彩评论