Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call my field validators in my save method in Django?

I have a model with a field that requires alphanumeric characters. I force this constraint using a validator. Something like this:

from django.core.validators import RegexValidator

validate_alphanumeric = RegexValidator(r'^[a-zA-Z0-9]*$', 'Only alphanumeric characters are allowed.')

class MyModel(models.Model):
    my_field = models.CharField(max_length=255, validators=[validate_alphanumeric,]

    def save(self, *args, **kwargs):
        # self.call_validators() or whatever
        super(MyModel, self).save(*args, **kwargs)

Now, this works automatically in my admin site, and model forms. However, when I create objects from the shell, or lets say a manual API endpoint, then the validator is not enforced.

Is there a built-in function in django like the one in my comments that I can just call in my save method? Or do I have to manually validate my field again in the save method? Thanks.

like image 304
darkhorse Avatar asked Sep 14 '25 22:09

darkhorse


1 Answers

Here's the validating objects documentation. Basically, if you call an object's full_clean() method, you'll run all validations on the object. You can run only the individual field validators by calling self.clean_fields().

But in general, it's not good practice to add validation in the save() method. The reason is that in most Django apps, you'd create a form (a ModelForm) which would call the validation methods and be able to return something meaningful to the user when validation fails.

When the model's save() method is called it's too late to show something to the user, so you can only raise an exception at that point (and crash).

The normal procedure (which the admin forms use) is: validate the form by calling form.is_valid() (which calls full_clean() on the model), then if and only if the form is valid, save the model.

The shell is not the regular interaction method and should be used only very carefully as it bypasses the normal flow of the application.

like image 169
dirkgroten Avatar answered Sep 17 '25 20:09

dirkgroten



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!