Reputation: 489
A silly question: why do we get TypeError
on the super
's __init__
only? Aren't they supposed to take the same arguments?
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
# self.request = kwargs.pop('request')
super().__init__(*args, **kwargs)
If it's the same method of the same forms.ModelForm
class, why does the first one accept request
and the second doesn't?
Here's ModelForm
's __init__
:
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=None,
empty_permitted=False, instance=None, use_required_attribute=None,
renderer=None):
So when I'm calling form = MyModelForm(request=request)
why does the MyModelForm
's __init__
let it through?
Upvotes: 3
Views: 7289
Reputation: 18456
why do we get TypeError on the super's init only? Aren't they supposed to take the same arguments?
No, they are not.
When you are creating your ModelForm class, its constructor's signature is def __init__(self, *args, **kwargs)
, so there is not any keywords, just **kwargs
that allows any number of keyword arguments to be passed while creating the instance of the MyModelForm
class.
The second function signature is coming from the django ModelForm
class, which has limited number of keyword arguments, and only those keyword arguments are accepted. You can try passing some random kwargs, like foo='bar'
, it will again throw error.
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=None,
empty_permitted=False, instance=None, use_required_attribute=None,
renderer=None):
But if it also had **kwargs
in the end, then it'd also accept any keyword arguments.
Upvotes: 5