Search code examples
djangodjango-viewsdjango-generic-views

What is the difference between use fields attribute and use a FormClass in Django CreateView?


What is the difference between use:

class FooCreateView(CreateView):
   model = Foo
   fields = (f,o,o)

and

class FooCreateView(CreateView):
   model = Foo
   form_class = FooForm

Solution

  • The difference is that in the second you need to define a FooForm class that must inherit from Django ModelForm class and have a model = Foo, this mechanism allows you to implement extra validations over your form (i.e. by defining methods like: def clean_f(self), def clean_o(self))

    As you can see, you don't need to specify the fields attribute in the CreateView subclasss if using a form_class, because Django will take the form_class fields and use it.

    Example:

    models.py

    from django.db import models
    
    class Foo(models.Model):
        f = models.CharField(max_length=10)
    

    forms.py

    from django import forms
    from appname.models import Foo
    
    class FooForm(forms.ModelForm):
        class Meta:
            model = Foo
            fields = '__all__'  # shortcut to add all Foo fields.
    
        def clean_f(self):
            if 'M' not in self.cleaned_data['f']:
                raise forms.ValidationError('M char must be in f attribute')
            return self.cleaned_data['f']
    

    views.py

    from django.views.edit import CreateView
    from appname.forms import FooForm
    
    class FooCreateView(CreateView):
        model = Foo
        form_class = FooForm
    

    This will raise a ValidationError if you try to save a Foo instance which does not contains a 'M' in their f attribute.