Externally add form errors in Django

I have a Django form that will add a record to the database with a unique restriction on one of the columns. If an attempt occurs when trying to create a duplicate, I get a django.db.utls.IntegrityError message in which I violated a unique constraint (fortunately).

When processing Django forms, there are several validation methods:

  • Override the class method clean
  • Override the class method < clean_<field>

If the clear_<field> method calls django.forms.ValidationError , the error message will be added to the list in the _errors dictionary under the field name. When using the clean method, errors must be manually inserted into the _errors dict.

Now the clean and clean_<field> methods do not look like a nice place to post code that has side effects, and I'm afraid that checking at this point whether the value is unique does not guarantee that I will not get IntegrityError s. I would rather actually try to create a row in the database and give a form error message if the constraint is violated.

My main problem is that forms expose the public property errors , which is read-only . Therefore, I must, according to the documents, add a method to my form that does all the work, try to insert into the database and register an error when creating an IntegrityError . Since the action that processes the form after validation requires a lot of other data, I don’t want to put the code inside the form class itself.

Is there any other (documented or not) way to add an entry to the errors dict from outside the class, or should I just access the _errors "private" variable and be happy with it? I know this sounds like a violation of OOP, but creating an extra method just to access this "private" variable doesn't look like it is protecting anyone from anything.

Edit: It looks like someone has already raised a similar question , but it seems that the answers indicate manual insertion into _errors ...

+6
django django-forms
source share
2 answers

Now a simple solution is this:

 try: # Try to save model instance, which might throw `IntegrityError`. # ... except django.db.utils.IntegrityError: # The form passed validation so it has no errors. # Use the `setdefault` function just in case. errors = django.forms.util.ErrorList() errors = form._errors.setdefault( django.forms.forms.NON_FIELD_ERRORS, errors) errors.append('Sorry, this username is already in use.') 
+7
source share

I think adding a method to a form is quite reasonable. The ModelForm class, which has a save () method that executes the logic of saving the created instance in the database. If your form can inherit from ModelForm (or just add the save () method to your form), you will still be within the "djangonian" standards.

http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

0
source share

All Articles