Code

Opened 6 years ago

Closed 6 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:

Description

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
'happiness'
>>> overriding_form = OverridingModelForm(instance = model)
>>> overriding_form.instance.my_field
''
>>> 

Attachments (0)

Change History (1)

comment:1 Changed 6 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)

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.