personal web log written by izabeera and dryobates

django tricks

Bug with saving formsets in Django 1.6

by izabeera

If you have a model that has primary key which is also a foreign key to other model (e.g. case with inherited models), then you get an error while saving formsets built on them. Primary key value isn't converted correctly to python value.

That bug was fixed in Django 1.7 (, but it still exists in Django 1.6.

Monkey patch for that case:

def _get_to_python(self, field):
    while field.rel is not None:
        field = field.rel.get_related_field()
    return field.to_python

def _construct_form(self, i, **kwargs):
    if self.is_bound and i < self.initial_form_count():
        pk_key = "%s-%s" % (self.add_prefix(i),
        pk =[pk_key]
        pk_field =
        to_python = self._get_to_python(pk_field)
        pk = to_python(pk)
        kwargs['instance'] = self._existing_object(pk)
    if i < self.initial_form_count() and 'instance' not in kwargs:
        kwargs['instance'] = self.get_queryset()[i]
    if i >= self.initial_form_count() and self.initial_extra:
        # Set initial values for extra forms
            kwargs['initial'] = self.initial_extra[i - self.initial_form_count()]
        except IndexError:
    return super(BaseModelFormSet, self)._construct_form(i, **kwargs)

BaseModelFormSet._get_to_python = _get_to_python 
BaseModelFormSet._construct_form = _construct_form

Iza Kartowicz-Stolarska. IT engineer. I work in programming since 2005. During this time I gained wealth of experience in writing web applications... and loved Python and Vim :) I enjoy working with people which have positive attitude to the world. Email:


Tag cloud