没有自定义表单的Django模型字段验证

时间:2022-04-14 07:44:35

I am using a django DateField in my model.

我在我的模型中使用django DateField。

class CalWeek(models.Model):
  start_monday = models.DateField(verbose_name="Start monday")

I have a custom validation method that is specific to my modelField: I want to make sure that it is actually a Monday. I currently have no reason to use a custom ModelForm in the admin--the one Django generates is just fine. Creating a custom form class just so i can utilize the clean_start_monday(self)1 sugar that django Form classes provide seems like a lot of work just to add some field validation. I realize I can override the model's clean method and raise a ValidationError there. However, this is not ideal: these errors get attributed as non-field errors and end up at the top of the page, not next to the problematic user input--not an ideal UX.

我有一个特定于我的modelField的自定义验证方法:我想确保它实际上是星期一。我目前没有理由在管理员中使用自定义ModelForm - Django生成的一个就好了。创建一个自定义表单类只是为了我可以利用django Form类提供的clean_start_monday(self)1糖似乎只是添加一些字段验证的很多工作。我意识到我可以覆盖模型的clean方法并在那里引发ValidationError。然而,这并不理想:这些错误归结为非字段错误并最终位于页面顶部,而不是有问题的用户输入旁边 - 不是理想的用户体验。

Is there an easy way to validate a specific model field and have your error message show up next to the field in the admin, without having to use a custom form class?

是否有一种简单的方法来验证特定的模型字段,并在管理员的字段旁边显示您的错误消息,而不必使用自定义表单类?

1 个解决方案

#1


15  

You can look into Django Validators.

你可以看看Django Validators。

https://docs.djangoproject.com/en/dev/ref/validators/

https://docs.djangoproject.com/en/dev/ref/validators/

You would put the validator before the class, then set the validator in the Field.

您可以将验证器放在类之前,然后在Field中设置验证器。

def validate_monday(date):
    if date.weekday() != 0:
        raise ValidationError("Please select a Monday.")

class CalWeek(models.Model):
    start_date = models.DateField(validators=[validate_monday])

#1


15  

You can look into Django Validators.

你可以看看Django Validators。

https://docs.djangoproject.com/en/dev/ref/validators/

https://docs.djangoproject.com/en/dev/ref/validators/

You would put the validator before the class, then set the validator in the Field.

您可以将验证器放在类之前,然后在Field中设置验证器。

def validate_monday(date):
    if date.weekday() != 0:
        raise ValidationError("Please select a Monday.")

class CalWeek(models.Model):
    start_date = models.DateField(validators=[validate_monday])