Search code examples
pythondjangodjango-class-based-views

How do you modify form data before saving it while using Django's CreateView?


I'm using the CreateView of Django and I'm trying to find out how I can modify any text which gets sent before it gets saved. For example, right now I'm only looking to lowercase all the text before saving.

I know I need to use form_valid() but I can't seem to get it right.

forms.py

class ConfigForm(forms.ModelForm):
    class Meta:
        model  = Config
        fields = ["heading", "name", "data", "rating"]

views.py

def form_valid(self, form):
    super().form_valid(form)
    form.fields["heading"].lower()
    form.fields["name"].lower()
    form.fields["data"].lower()

Solution

  • That shouldn't be done in form_valid. You should do that in the form itself. Instead of letting CreateView automatically create a form for you, do it explicitly and overwrite the clean method.

    class MyForm(forms.ModelForm):
       class Meta:
          model = MyModel
          fields = ('list', 'of', 'fields')
    
       def clean(self):
           for field, value in self.cleaned_data.items():
               self.cleaned_data['field'] = value.lower()
    

    ...

    class MyCreateView(views.CreateView):
        form_class = MyForm