Opened 8 years ago

Closed 8 years ago

#6473 closed (worksforme)

Overriding ModelForm __init__ messes up instance

Reported by: yourcelf Owned by: nobody
Component: Forms Version: master
Severity: Keywords: ModelForm __init__ instance
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


Here's a model and two ModelForm classes for it:

from django import newforms as forms
from django.newforms import ModelForm
from django.db import models

class MyModel(models.Model):
    my_field = models.CharField(max_length = 50)

class NormalModelForm(ModelForm):
    class Meta:
        model = MyModel

class OverridingModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(OverridingModelForm, self).__init__(args, kwargs)
    class Meta:
        model = MyModel

"NormalModelForm" behaves as expected. However, "OverridingModelForm" which overrides __init__ loses the data in its "instance", even though it calls super.__init__.

Test case:

>>> model = MyModel(my_field = 'happiness')
>>> normal_form = NormalModelForm(instance = model)
>>> normal_form.instance.my_field
>>> overriding_form = OverridingModelForm(instance = model)
>>> overriding_form.instance.my_field

Change History (1)

comment:1 Changed 8 years ago by gwilson

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to worksforme
  • Status changed from new to closed

Your super call should be:

super(OverridingModelForm, self).__init__(*args, **kwargs)
Note: See TracTickets for help on using tickets.
Back to Top