Reputation:
Wrt to the code snippet below, why is super().__init__
used in the model? How does it work?
model.py
class DuckForm(forms.ModelForm):
class Meta:
model = Duck
fields = ('description', 'name')
def __init__(self, community, *args, **kwargs):
super().__init__(*args, **kwargs)
self.community = community
def save(self, commit=True):
duck = super().save(commit=False)
if not duck.community_id:
duck.community = self.community
if commit:
duck.save()
return duck
views.py
def add_duck(request):
if request.method == 'POST':
form = DuckForm(request.animal.community, data=request.POST)
if form.is_valid():
duck = form.save()
return redirect('DuckData')
else:
form = DuckForm(request.user.community)
return TemplateResponse(request, 'MyDuck.html', {'form': form})
Upvotes: 0
Views: 1045
Reputation: 604
Calling super.method
calls the method
method of the parent class, in this case ModelForm
. This is necessary in this case because Django models and forms have all sorts of strange things that happen to them in the __init__
method, and if you don't call super().__init__()
those won't happen and the object won't behave as expected.
Also as a side note, this is invalid syntax in python 2 (but completely valid and correct in python 3). You would have to write super(DuckForm, self).__init__
to achieve the same goal.
Upvotes: 4