Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django doesn't validate on create?

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?

like image 808
smilebomb Avatar asked Jul 28 '16 15:07

smilebomb


People also ask

How do I check if a form is valid in Django?

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.

What is validation error in Django?

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.

What is clean 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.

How does Django validate email?

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.


1 Answers

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.

like image 106
ultrajohn Avatar answered Sep 28 '22 17:09

ultrajohn