Skip to content
Advertisement

Django – CreateView specifying a form to use from forms.py

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?

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement