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 ...
django django-forms
André caron
source share