Django admin Valid form with funtion clean

Question:

In my django model I defined a clean function to validate additional conditions before saving the data.

Here is my model:

class TestRange(models.Model):
    SERVICE = [
        ('s1', 'Service 1'),
        ('s2', 'Service 2')
    ]

    service = models.CharField(max_length=2, choices=SERVICE)
    SDA = [
        (False, 'NO SDA'),
        (True, 'SDA')
    ]
    sda = models.BooleanField(choices=SDA)
    number_start = models.CharField(max_length=10, validators=[valide_phone_number])
    number_end = models.CharField(max_length=10, validators=[valide_phone_number])

    def clean(self):
        if int(self.number_end) < int(self.number_start):
            raise ValidationError({'number_end': _("The end number must be greater than or equal to the start number")})
        if self.sda and len(self.number_start)!=10:
            raise ValidationError({'number_start': _("A SDA number consists of 10 digits")})
        super(TestRange, self).clean()

Since the definition of this function the default validation of the admin form no longer works, I no longer have to check the fields of the form before registration.

So I got an error message:

invalid literal for int() with base 10: ''

Request Method:     POST
Request URL:    http://127.0.0.1:8000/admin/gestnum/testrange/add/
Django Version:     4.1
Exception Type:     ValueError
Exception Value:    

invalid literal for int() with base 10: ''

Exception Location:     C:UsersuserDocumentsDEVtesttestmodelsTestRange.py, line 25, in clean
Raised during:  django.contrib.admin.options.add_view
Python Executable:  C:UsersuserDocumentsDEVtest.venvScriptspython.exe
Python Version:     3.9.6

how to proceed to keep the default validation and add my additional validation

without the function:

defaut validate adminform

Do you have a solution ? Without defining a new form

Thanks

Asked By: Mickaël Pelé

||

Answers:

Try to define your clean method this way:

    def clean(self):
        number_start = int(self.number_start) if self.number_start.isnumeric() else 0
        number_end = int(self.number_end) if self.number_end.isnumeric() else 0
        if number_end < number_start:
            raise ValidationError({'number_end': _("The end number must be greater than or equal to the start number")})
        if self.sda and len(f'{number_start}') != 10:
            raise ValidationError({'number_start': _("A SDA number consists of 10 digits")})
        super().clean()

When you enter data with admin panel the self.number_start and self.number_end fields are probably empty because you don’t filled them with any integer value. Also I think the number_start and number_end fields should be IntegerField type that makes this problem not-existing.

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.