没有自定义表单的Django模型字段验证 [英] Django model field validation without a custom form
问题描述
class CalWeek(models.Model):
start_monday = models.DateField(verbose_name =开始星期一)
我有一个特定于我的modelField的自定义验证方法:我想确保它实际上是星期一我目前没有理由在管理员中使用一个自定义的ModelForm - 一个Django生成就行了。创建一个自定义表单类,以便我可以使用 clean_start_monday(self)
1 django表单类提供的糖似乎很多工作只是为了添加一些字段验证。我意识到我可以覆盖模型的干净方法,并在那里提出一个 ValidationError
。但是,这不是理想的:这些错误被归因为非字段错误,并且最终位于页面顶部,而不是问题用户输入旁边 - 不是理想的UX。
有没有一种简单的方法验证一个特定的模型字段,并在管理员的字段旁边显示错误消息,而不必使用自定义表单类?
您可以查看Django验证器。
https://docs.djangoproject.com/en/dev/ref/validators/
您可以将验证器放在课程之前,然后在Field中设置验证器。
def validate_monday(date):
如果date.weekday()!= 0:
raise ValidationError(请选择一个星期一)
class CalWeek(models.Model) :
start_date = models.DateField(validators = [validate_monday])
I am using a django DateField in my model.
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.
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?
You can look into Django Validators.
https://docs.djangoproject.com/en/dev/ref/validators/
You would put the validator before the class, then set the validator in the 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])
这篇关于没有自定义表单的Django模型字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!