Home > Software design >  Django - CreateView specifying a form to use from forms.py
Django - CreateView specifying a form to use from forms.py

Time:07-18

I'm trying to use a form I have defined in forms.py within my CreateView, as I have css classes and field labels I want to apply.

Documentation states declaring a form_class field within your CreateView, but trying to set it as my ModelForm gives me the error TypeError 'AssessmentForm' object is not callable

class AssessmentCreateView(LoginRequiredMixin, generic.CreateView):
    model = Assessment
    form_class = AssessmentForm()
...

What is the proper implementation of setting a ClassBasedView to use a ModelForm?

CodePudding user response:

The reason you are getting this error is that you are calling this AssessmentForm(). So instead of using this

form_class = AssessmentForm()

use this:

form_class = AssessmentForm

And if you deep dive into CreateView you came to know that this class is using FormMixin that has a method name get_form, with the implementation something like this.

def get_form(self, form_class=None):
    """Return an instance of the form to be used in this view."""
    if form_class is None:
        form_class = self.get_form_class()
    return form_class(**self.get_form_kwargs())

and get_form_class() simply returns your self.form_class, something like this.

def get_form_class(self):
    """Return the form class to use."""
    return self.form_class
  • Related