我在mt tithe模型中有一个称为keyChecker的字段。 KeyChecker是唯一的,仅在提交表单后才生成(通过pre_save信号)。现在的问题是,当键不存在时,所有内容都会保存,但是当键存在时,它会引发IntegrityError,这是预期的。但是,只要引发此错误,我都希望将用户重定向到url。
Models.py
class Tithe(models.Model):
YEAR = []
for r in range((datetime.datetime.now().year), (datetime.datetime.now().year+10)):
YEAR.append((r,r))
MONTHS = (
('January', 'January'),
('February', 'February'),
('March', 'March'),
('April', 'April'),
('May', 'May'),
('June', 'June'),
('July', 'July'),
('August', 'August'),
('September', 'September'),
('October', 'October'),
('November', 'November'),
('December', 'December'),
)
year = models.IntegerField( choices=YEAR, default=datetime.datetime.now().year)
month = models.CharField(max_length = 50, choices = MONTHS, null=True, blank=True)
week1 = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
week2 = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
week3 = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
week4 = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
total = models.DecimalField(max_digits=10, decimal_places=2, default = 0)
keyChecker = models.CharField(max_length=500,unique=True, null=True, blank=True)
member = models.ForeignKey('Member', on_delete = models.CASCADE)
def __str__(self):
return "{0}_{1}_{2}".format(self.member, self.year, self.month)
def get_absolute_url(self):
return reverse('tithe', kwargs={'slug': datetime.datetime.now().year, 'slug2':datetime.datetime.now().month})
def get_key_checker(instance, new_slug = None):
memberpk = instance.member_id
member = Member.objects.get(pk = memberpk)
fname = member.fname
lname = member.lname
contact = member.contact
year = instance.year
month = instance.month
keyChecker = "{0}_{1}_{2}_{3}_{4}".format(fname,lname,contact,year,month)
return keyChecker
def pre_save_tithe_receiver(sender, instance, *args, **kwargs):
instance.keyChecker = get_key_checker(instance)
pre_save.connect(pre_save_tithe_receiver, sender=Tithe)