我在其中一个模型上进行了一些自定义验证,并根据验证失败生成错误。我想将这些错误传递给我。
class TimeSheet(models.Model):
O = "Open"
S = "Submitted"
A = "Approved"
R = "Needs review"
STATUS_CHOICES = (
(O, "Open"),
(S, "Submitted"),
(A, "Approved"),
(R, "Needs Reviewing"),
)
start_date = models.DateField()
end_date = models.DateField()
person_id = models.ForeignKey(Person)
status = models.CharField(max_length= 50, default="Open", choices=STATUS_CHOICES)
submitted_id = models.IntegerField(default=0)
approved_id = models.IntegerField(default=0)
submitted_date = models.DateTimeField(auto_now_add=True, blank=True)
approved_date = models.DateTimeField(auto_now_add=True, blank=True)
def get_absolute_url(self):
return reverse('tande:timesheet', kwargs={'id': self.id})
def save(self, *args, **kwargs):
ok_to_continue = True
start_date = self.start_date
end_date = self.end_date
if end_date < start_date:
error = "ERROR: Start date must be before end date"
ok_to_continue = False
# make sure both dates are in the same month
if start_date.month != end_date.month:
error = "ERROR: Start and end dates must be in the same month"
ok_to_continue = False
# VALIDATION
if ok_to_continue:
super(TimeSheet, self).save(*args, **kwargs)
else:
print error
self.request.session['error_from_save'] = error
但是,这会引发错误:
AttributeError:'TimeSheet'对象没有属性'request'
为什么self.request.session
无效?有没有其他方法可以将其传回我的观点?
答案 0 :(得分:3)
覆盖模型的save()
方法不是执行验证的首选方法。您应该为模型中的每个字段提供validators
属性,并为其提供custom-written validators,或者在override the clean_fieldname
methods of your form的(模型)表单中进行验证。
您无法从模型的保存方法将内容传递回视图的原因是可能无法始终从视图中调用save方法。例如,它可以从shell调用。因此,不会总是将视图或会话返回到。