0

I found this
How to properly overwrite clean() method and this
Can `clean` and `clean_fieldname` methods be used together in Django ModelForm?
but it seems to work differently if one is using the generic class mixins ModelFormMixin.
My class is also derived from ProcessFormView.
Is def form_valid(self, form): the only point where I can overwrite the form handling process?

sebhaase
  • 564
  • 1
  • 6
  • 10

1 Answers1

1

You are confusing views and forms. A CreateView for example makes use of a ModelForm to create an object. But instead of letting the view construct the ModelForm, you can specify such form yourself and then pass this as form_class to the view.

For example say you have a Category model with a name field, and you wish to validate that the name of the Category is all written in lowercase, you can define a ModelForm to do that:

from django import forms
from django.core.exceptions import ValidationError

class CategoryForm(forms.ModelForm):

    def clean_name(self):
        data = self.cleaned_data['recipients']
        if not data.islower():
            raise ValidationError('The name of the category should be written in lowercase')
        return data

    class Meta:
        model = Category
        fields = ['name']

now we can plug in that ModelForm as form for our CategoryCreateView:

from django.views.generic import CreateView

class CategoryCreateView(CreateView):
    model = Category
    form_class = CategoryForm

The validation thus should be done in the ModelForm, and you can then use that form in your CreateView, UpdateView, etc.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555