views:

216

answers:

2

I have a model for which the need is to show the form multiple times. I have used it under a modelformset. I seem to have a problem with the id of this model which is also the primary key for the model.
I prepopulate the formset with data which I wish to edit.
But whenever I click on submit it refreshes the page back with an error saying '(Hidden field id) with this None already exists.'
This error comes specifically for the 'id' field which is hidden

<input type="hidden" id="id_form-0-id" value="2972" name="form-0-id"/>

This is the snippet from the template. (I got it from firebug) What could the issue possibly be since the form is invalid I am not able to save the data.

ProfilesFormSet = modelformset_factory(Profile,exclude = ( <items spearated by commas>), extra=0) 
profile_form_set = ProfilesFormSet(queryset = Profile.objects.filter(userprofile=userprofile).order_by('-modified_on'))

This is the code snippet.

A: 

I believe this error is caused by one of the following:

  • The Django form object you are using inside the formset does not include the primary key (id) of the model. However, since you are using modelformset_factory this shouldn't be the case (you also wouldn't be getting that error message).

  • The HTML form in your template does not include the primary key, even as a hidden field. Make sure you have {{ form.id }} or something like that in your template, inside the {{ for form in formset }} loop.

I can't think of any more reasons at the moment, but I'm sure they are all going to be related to the form POST'ed back from the browser client is missing the id field somehow.

Van Gale
+1  A: 

If you're using PostgreSQL and any version of Django prior to 1.1beta, and your model does not have a default ordering defined, I think you're probably seeing the bug related to inconsistent ordering of objects returned from the database (see Django Trac tickets 9076, 9758, 10163 among others).

Try setting a default ordering on the model:

class Meta:
    ordering = ('some_field',)

See if that fixes it.

Carl Meyer