Django: Validation error in Admin
- by tomwolber
NEWBIE ALERT!
background:
For the first time, I am writing a model that needs to be validated. I cannot have two Items that have overlapping "date ranges". I have everything working, except when I raise forms.ValidationError, I get the yellow screen of death (debug=true) or a 500 page (debug=false).
My question:
How can I have an error message show up in the Admin (like when you leave a required filed blank)?
Sorry for my inexperience, please let me know if I can clarify the question better.
Models.py
from django.db import models
from django import forms
from django.forms import ModelForm
from django.db.models import Q
class Item(models.Model):
name = models.CharField(max_length=500)
slug = models.SlugField(unique=True)
startDate = models.DateField("Start Date", unique="true")
endDate = models.DateField("End Date")
def save(self, *args, **kwargs):
try:
Item.objects.get(Q(startDate__range=(self.startDate,self.endDate))|Q(endDate__range=(self.startDate,self.endDate))|Q(startDate__lt=self.startDate,endDate__gt=self.endDate))
#check for validation, which may raise an Item.DoesNotExist error, excepted below
#if the validation fails, raise this error:
raise forms.ValidationError('Someone has already got that date, or somesuch error message')
except Item.DoesNotExist:
super(Item,self).save(*args,**kwargs)
def __unicode__(self):
return self.name
def get_absolute_url(self):
return "/adtest/%s/" % self.slug