Reputation: 888
I have some custom validation on one of my models, and I generate errors based on which validation failed. I want to pass these errors to my view.
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
However, this raises the error:
AttributeError: 'TimeSheet' object has no attribute 'request'
Why is self.request.session
not working? Is there another way to pass this back to my view?
Upvotes: 1
Views: 47
Reputation: 2153
Overriding the model's save()
method is not the preferred way to do validation. You should either provide a validators
attribute to each field in your model and provide them with custom-written validators, or do the validation in the (Model)Form where you override the clean_fieldname
methods of your form.
The reason you can't pass things back to the view from the model's save method is that the save method may not always be called from a view. It may be called from the shell, for example. So there wouldn't always be a view or a session to return things to.
Upvotes: 3