frlan
frlan

Reputation: 7260

Django: How to handle error at custom form_valid() correctly

What is the "correct" way on handle errors inside a custom form_valid() function?

E.g. I'm having a view which is having this form_valid() method defined:

class StorageItemMergeView(FormView):
# ...

def form_valid(self, form):
    si = StorageItem.objects.get(pk=self.kwargs["pk"])
    si.part.merge_storage_items(si, StorageItem.objects.get(
                                  pk=self.request.POST["storageitem1"]
                                  )
                               )
    return super(StorageItemMergeView, self).form_valid(form)

The form for this is quiet minimal:

class MergeStorageItemsForm(forms.Form):
    storageitem1 = forms.ModelChoiceField(queryset=StorageItem.objects.all())

As a matter of fact the user might fill in syntactical correct data which are failing at call of merge_storage_items().

In my case merge_storage_items() is able to return True or False -- but how to react correctly in case of the method call is failing?

Upvotes: 2

Views: 1326

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

The correct way is not to do it in form_valid at all. That's not what it's for. That method is called one the form has been validated and is responsible for saving and redirecting.

The right place to do this is in the form class itself, where you would override the clean method and raise forms.ValidationError if the check fails.

Upvotes: 1

Related Questions