Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the main difference between clean and full_clean function in Django model form?

What is the main difference between clean and full_clean function in Django model ?

like image 827
kamyarmg Avatar asked Jul 22 '18 17:07

kamyarmg


People also ask

What is clean method in Django?

The clean() method on a Field subclass is responsible for running to_python() , validate() , and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised.

Does Django save call clean?

save() calls the clean. This way the integrity is enforced both from forms and from other calling code, the command line, and tests. Without this, there is (AFAICT) no way to write a test that ensures that a model has a FK relation to a specifically chosen (not default) other model.

How can you validate Django model fields?

to_python() method of the models. Field subclass (obviously for that to work you must write custom fields). Possible use cases: when it is absolutely neccessary to ensure, that an empty string doesn't get written into the database (blank=False keyword argument doesn't work here, it is for form validation only)

What is forms Modelform in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.


2 Answers

From the documentation:

Model.full_clean(exclude=None, validate_unique=True):

This method calls Model.clean_fields(), Model.clean(), and Model.validate_unique() (if validate_unique is True), in that order and raises a ValidationError that has a message_dict attribute containing errors from all three stages.

Model.clean():

This method should be used to provide custom model validation, and to modify attributes on your model if desired.

For more detailed explanation, have a look at the Validating objects section of the documentation.

like image 90
Keyur Potdar Avatar answered Nov 07 '22 06:11

Keyur Potdar


they are not against each other usually you call Model.full_clean() to be able to trigger Model.clean() for costume validation for example:

from django.core.exceptions import ValidationError
from django.db import models


class Brand(models.Model):
    title = models.CharField(max_length=512)

    def clean(self):
        if self.title.isdigit():
            raise ValidationError("title must be meaningful not only digits")

    def save(self, *args, **kwargs):
        self.full_clean()
        return super().save(*args, **kwargs)
like image 31
amirbahador Avatar answered Nov 07 '22 06:11

amirbahador