Why signature of the form "save()" method should match base Form class in django?

1.4k views Asked by At

For instance, I have following code:

from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.views.generic import FormView


class MyModel(models.Model)
    owner = models.ForeignKey(User)
    description = models.TextField()


class MyForm(ModelForm):

    class Meta:
        model = MyModel

    def save(self, owner, commit=True):
        self.instance.owner = owner
        return super().save(commit)


class MyView(FormView):
    success_url = '/'
    form_class = MyForm
    template_name = 'my_template.html'

    def form_valid(self, form):
        form.save(self.request.user)
        return super().form_valid(form)

If I run pylint on that code, it gives following error:

[W0221(arguments-differ), MyForm.save] Arguments number differs from overridden 'save' method

Is it a bad practice to do that? Should I set owner in the view form_valid method?

1

There are 1 answers

1
user2839978 On

Take a look at the docs: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

Instead of using a different signature, why don't you call save with commit=False; this will return the model instance. You can then add the appropriate attributes, in this case owner, and save the model directly.