Alex Burla
Alex Burla

Reputation: 126

How to validate one field by another in a model in Django?

On saving data to the model I want to validate one field by another (they are in the same model). Here is my model:

class String(models.Model):
    key = models.CharField(max_length=60, unique=True)
    name = models.CharField(max_length=60)
    value = models.CharField(max_length=230)
    maxSize = models.PositiveSmallIntegerField()

I want to validate value field by max size taken from the maxSize field and return specific error to user when validation is failed. How to do that? :)

Upvotes: 1

Views: 1682

Answers (3)

Andrey Maslov
Andrey Maslov

Reputation: 1466

add your own validation method in model form

class FormString(forms.ModelField):
    class Meta:
        model = String
        fields = "__all__"

    def clean_value(self):
        value = self.cleaned_data.get("value")
        max_size = self.cleaned_data.get("maxSize")
        if value and max_size and len(value) > max_size:
            self.add_error("value", "length should be less then {}".format(max_size))
        return value

or you can have validation in your clean method

def clean(self):
    cleaned_data = super().clean()
    value = cleaned_data.get('value')
    max_size = cleaned_data.get("maxSize")
    if value and max_size and len(value) > max_size:
        self.add_error("value", "length should be less then {}".format(max_size))
    return cleaned_data

Upvotes: 3

Arjun Shahi
Arjun Shahi

Reputation: 7330

In your ModelForm You can use the clean method.

class StringModelForm(forms.ModelForm):
        # Everything as before.

        def clean(self):
          cleaned_data = super().clean()
          maxSize = cleaned_data.get("maxSize")
          value = cleaned_data.get("value")
          
          if maxSize = ... : #you logic here 
              raise ValidationError('your error message')
                

Upvotes: 2

Jochem F.
Jochem F.

Reputation: 46

If you're using a form see the docs. When raising a ValidationError you can inform the user with a custom message.

Upvotes: 1

Related Questions