开发者

django model save error message

开发者 https://www.devze.com 2023-01-20 13:52 出处:网络
i like to output an error message if this date allready exist. has someone an idea? class Bet(models.Model):

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

class Bet(models.Model):

name = models.CharField(max_leng开发者_Python百科th=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()


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".


Model validation is what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消