views:

22

answers:

2

hi,

i like to output an error message if this date allready exist. has someone an idea?

class Bet(models.Model):

name = models.CharField(max_length=30, verbose_name='Name')
date = models.DateTimeField(verbose_name='Datum')

def __unicode__(self):
    return self.name

def save(self):
    newDate = self.date

    try:
        Bet.objects.get(date=newDate)
        ## error message and return to form

    except Bet.DoesNotExist:
        super(Bet, self).save()
+1  A: 

You need to add date to unique_together in meta section of you model.

class Bet(models.Model):

    name = models.CharField(max_length=30, verbose_name='Name')  
    date = models.DateTimeField(verbose_name='Datum')  

    class Meta:
        unique_together = ('date')

Or to add unique to the date field:

class Bet(models.Model):
    name = models.CharField(max_length=30, verbose_name='Name')  
    date = models.DateTimeField(verbose_name='Datum', unique=True)         

In you logic for adding a bet you will have something like this:

def add_bet(request):  
    if request.method == 'POST':  
        bet_form = BetForm(request.POST)  
        if bet_form.is_valid():  
            #save bet  
        else:  
            create_user_message(request, "unsuccess", strip_tags(bet_form.non_field_errors())) 

Trying to add a bet with the same date will fail, printing a message like this: "A bet with this date already exists".

Seitaridis
thanks a lot, worked fine.
Roland
A: 

Model validation is what you need.

Daniel Roseman