[Answer]-Django: Check if user have added a new instance in the form?

1👍

Suppose your form has a name field for existing category names and a new_name field for the input box. In your form’s clean() method, you’ll want to check to see if self.cleaned_data has a value for new_name and act accordingly. You might do:

self.cleaned_data['name'] = self.cleaned_data['new_name']

for example.

Unless you override other field or form methods, the data in these fields are ‘safe’ as far as malicious input is concerned. If you raise a ValidationError in the form’s clean() method, is_valid() will return false. So, as long as you:

form = YourForm(...)
if form.is_valid():
    form.save()

The save() will not be called with invalid data.

👤DavidM

Leave a comment