views:

175

answers:

1

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    
+1  A: 

For Django 1.2 see http://docs.djangoproject.com/en/dev/ref/forms/validation/#using-validation-in-practice.

In versions prior to 1.2 you would have to make your own model form for your admin and put your validation methods there! http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute

from django import forms
from models import Item

class ItemForm(forms.ModelForm):

   class Meta:
       model = Item

   def clean(self, value):
       data = self.cleaned_data
       start = data['startDate']
       end =  data['endDate']
       try:
           item = Item.objects.get(Q(startDate__range=(start,end))|\
                                   Q(endDate__range=(start,end))|\
                                   Q(startDate__lt=start,endDate__gt=end))
           raise forms.ValidationError('.....')
       except:
           pass

   return data 

Then put in your admin form=ItemForm and make sure to define the form somewhere before! For a more detailled description see http://www.jroller.com/RickHigh/entry/django_admin_validation_of_multiple.
Further to assort to django conventions you should name your fields eg. end_date and not endDate. Guess you will not even need to specify their verbose_name then anymore!

lazerscience
I am using 1.2.1, and I've read that link. I still don't know how to use this in the Admin
tomwolber
There's also a new post here dealing with the same problem: http://stackoverflow.com/questions/2973442/how-do-you-make-django-form-validation-dynamic
lazerscience