Custom validation in Django admin

后端 未结 3 1770
北恋
北恋 2021-02-01 13:21

I have a very simple Django app in order to record the lectures given my colleagues.Since it is quite elementary,I am using the Django admin itself. Here is my models.py:

<
3条回答
  •  无人共我
    2021-02-01 13:38

    Usually you just want to define a clean() method on the model itself.

    https://docs.djangoproject.com/en/2.1/ref/models/instances/#validating-objects

    from django.core.exceptions import ValidationError
    
    class Lecture(models.Model):
        topic = models.CharField(max_length=100)
        speaker = models.CharField(max_length=100)
        start_date = models.DateField()
        end_date = models.DateField()
    
        def clean(self):
            if self.start_date > self.end_date::
                raise ValidationError("Dates are incorrect")
    

    Something like that will work in the django admin without any need to create a form class.

提交回复
热议问题