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 (https://github.com/django/django/commit/efb0100ee67931329f17bc9988ecd5f0619cea14), 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), self.model._meta.pk.name)
        pk = self.data[pk_key]
        pk_field = self.model._meta.pk
        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
        try:
            kwargs['initial'] = self.initial_extra[i - self.initial_form_count()]
        except IndexError:
            pass
    return super(BaseModelFormSet, self)._construct_form(i, **kwargs)


BaseModelFormSet._get_to_python = _get_to_python 
BaseModelFormSet._construct_form = _construct_form

izabeera
izabeera
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: iza@stolarscy.com

Archive

Tag cloud