Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Django, auto setting a field during a save, based on other Admin page inputs
- class Suffix(models.Mode):
- suffix = models.CharField(max_length=255)
- def __unicode__(self):
- return u'%s'%(self.suffix)
- class Person(models.Model):
- first_name= models.CharField(max_length=255)
- last_name= models.CharField(max_length=255)
- suffixes= models.ManyToManyField(Suffix, blank=True, null=True)
- full_name= models.CharField(max_length=255)
- class SuperPerson(Person):
- ignore_this_field= model.CharField(max_length=255)
- def save(self, *args, **kwargs):
- # Attempt to get data into the database so I can access it
- super(SuperPerson,self).save(*args,**kwargs)
- self.full_name = self.first_name + self.last_name
- for suf in self.suffixes.all():
- self.full_name+= suf.__unicode__()
- # Now save the copy with full_name set as I wish
- super(SuperPerson,self).save(*args,**kwargs)
- @receiver(pre_save, sender=SuperPerson)
- def set_full_name(sender, instance, **kwargs):
- instance.full_name = instance.first_name + instance.last_name
- for suf in instance.suffixes.all():
- instance.full_name+= ', ' + suf.__unicode__()
- @receiver(m2m_changed, sender=Person.suffixes.through)
- def set_full_name_after_ManyToMany_saved(sender, instance, **kwargs):
- instance.full_name = instance.first_name + instance.last_name
- for suf in instance.suffixes.all():
- instance.full_name+= ', ' + suf.__unicode__()
- print 'Saving As', instance.full_name
- instance.save()
Add Comment
Please, Sign In to add comment