Is it the case that the create
function doesn't validate according to the model specifications? Here's my model:
class Contact(models.Model):
id = models.AutoField(primary_key=True)
firstname = models.CharField(max_length=100, null=False, blank=False)
lastname = models.CharField(max_length=100, null=False, blank=False)
email = models.EmailField(max_length=150, blank=False, null=False)
active = models.BooleanField(default=True)
And I use this function in my view
:
new_contact = Contact.objects.create(firstname=a,
lastname=b,
email=c)
# where a, b, & c are empty strings in request.POST, which shouldn't validate
The call to create
goes through without a problem. But, that shouldn't be the case. The model specifies those fields as required. In fact, if I go to the admin panel and view this object, I can't save it (without making any changes) because it yells at me that the fields are required.
Is it normal behavior for create
to not validate?
How can I force it to validate?
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
A validator is a callable that takes a value and raises a ValidationError if it doesn't meet some criteria. Validators can be useful for reusing validation logic between different types of fields.
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.
Django provides several validation methods for checking email address validity. The easiest way is to import the validate_email method from the core validators module. This is a standalone function that can be used in any models, forms, or views.
From Django's doc, it says that you need to explicitly call model validation related methods i.e., full_clean, clean
, for model validation to take effect.
You can follow the examples available in Django documentation to implement your own validation sequence in your model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With