Skip to content Skip to sidebar Skip to footer

Django Doesn't Call Model Clean Method

I have a view, which creates models from CSV file. I've added clean method to the model class definition, but it isn't called when model is created. Here is example of models.py: c

Solution 1:

To call the model clean method we will override save method. Check the link: https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.clean

classCommonMeasurement(models.Model):
    timestamp = models.DateTimeField()
    value = models.FloatField()
    run = models.ForeignKey(Run)

    defclean(self):
        if self.timestamp < self.run.timestamp_start or self.timestamp > self.run.timestamp_end:
            raise django_excetions.ValidationError('Measurement is outside the run')

    defsave(self, *args, **kwargs):
        self.full_clean()
        returnsuper(CommonMeasurement, self).save(*args, **kwargs)

Solution 2:

I've found a solution to override method:

classCommonMeasurement(models.Model):
    timestamp = models.DateTimeField()
    value = models.FloatField()
    run = models.ForeignKey(Run)

    objects = models.Manager()
    analyzes = managers.MeasureStatManager()

    defsave(self, **kwargs):
        self.clean()
        returnsuper(CommonMeasurement, self).save(**kwargs)

    defclean(self):
        super(CommonMeasurement, self).clean()
        print'here we go'if self.timestamp < self.run.timestamp_start or self.timestamp > self.run.timestamp_end:
            raise django_excetions.ValidationError('Measurement is outside the run')

But I'm not sure that it can be a good decision.

Solution 3:

Solution 4:

Apparently in newer versions of Django the ModelForm.full_clean does call it's instance's full_clean method:

Post a Comment for "Django Doesn't Call Model Clean Method"