[英]ValidationError in Django
Hi I am very new at Django.嗨,我是 Django 的新手。 I am working on a small project in which i am using modelform.
我正在做一个使用modelform 的小项目。 For date field i want to do custom validation ie whenever a user enter a date before today's date it should display a error message near date field.
对于日期字段,我想做自定义验证,即每当用户输入今天日期之前的日期时,它应该在日期字段附近显示一条错误消息。 I have written code as per the django's documentation, but it gives ValidationErrors for the raise statement in modelform.
我已经按照 django 的文档编写了代码,但它为模型形式的 raise 语句提供了 ValidationErrors。 like ValidationError at /add_task/ [u"Please enter valid date. Either today's date or after that."]
像 /add_task/ 处的 ValidationError [u"请输入有效日期。今天的日期或之后的日期。"]
Please help me how to overcome this problem.请帮助我如何克服这个问题。 Thanks in advance.
提前致谢。
Codes of my models:我的模型代码:
from django.db import models
class MyTask(models.Model):
summary=models.CharField(max_length=100)
description=models.CharField(max_length=500)
due_date=models.DateField(null=True)
completed_status=models.BooleanField()
def __unicode__(self):
return self.summary
Codes of my modelform:我的模型代码:
from django.forms import ModelForm, Textarea
from django.forms.extras.widgets import SelectDateWidget
from django.core.exceptions import ValidationError
from assignment.models import MyTask
import datetime
class AddTaskForm(ModelForm):
class Meta:
model=MyTask
fields=('summary','description','due_date')
widgets = {
'description': Textarea(attrs={'cols': 50, 'rows': 10}),
'due_date':SelectDateWidget(),
}
def get_due_date(self):
diff=self.cleaned_data['due_date']-datetime.date.today()
if diff.days<0:
raise ValidationError("Please enter valid date. Either today's date or after that.")
else:
return self.cleaned_data['due_date']
def get_summary(self):
return self.cleaned_data['summary']
def get_description(self):
return self.cleaned_data['description']
Your validation method needs to be called clean_due_date
.您的验证方法需要称为
clean_due_date
。 In Django < 3 it should raise forms.ValidationError
, but in Django 3 it should use core.exceptions.ValidationError
.在 Django < 3 中它应该引发
forms.ValidationError
,但在 Django 3 中它应该使用core.exceptions.ValidationError
。
I have no idea what the get_summary
and get_description
methods are for, they aren't called and don't do anything useful.我不知道
get_summary
和get_description
方法是做什么的,它们没有被调用,也没有做任何有用的事情。
See the Django 3 docs here and the Django 2 docs here .见Django的3个文档这里和Django的2文档这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.