Guest User

Untitled

a guest
Aug 10th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. Django, auto setting a field during a save, based on other Admin page inputs
  2. class Suffix(models.Mode):
  3. suffix = models.CharField(max_length=255)
  4. def __unicode__(self):
  5. return u'%s'%(self.suffix)
  6.  
  7. class Person(models.Model):
  8. first_name= models.CharField(max_length=255)
  9. last_name= models.CharField(max_length=255)
  10. suffixes= models.ManyToManyField(Suffix, blank=True, null=True)
  11. full_name= models.CharField(max_length=255)
  12.  
  13. class SuperPerson(Person):
  14. ignore_this_field= model.CharField(max_length=255)
  15.  
  16. def save(self, *args, **kwargs):
  17. # Attempt to get data into the database so I can access it
  18. super(SuperPerson,self).save(*args,**kwargs)
  19.  
  20. self.full_name = self.first_name + self.last_name
  21. for suf in self.suffixes.all():
  22. self.full_name+= suf.__unicode__()
  23.  
  24. # Now save the copy with full_name set as I wish
  25. super(SuperPerson,self).save(*args,**kwargs)
  26.  
  27. @receiver(pre_save, sender=SuperPerson)
  28. def set_full_name(sender, instance, **kwargs):
  29. instance.full_name = instance.first_name + instance.last_name
  30.  
  31. for suf in instance.suffixes.all():
  32. instance.full_name+= ', ' + suf.__unicode__()
  33.  
  34. @receiver(m2m_changed, sender=Person.suffixes.through)
  35. def set_full_name_after_ManyToMany_saved(sender, instance, **kwargs):
  36. instance.full_name = instance.first_name + instance.last_name
  37. for suf in instance.suffixes.all():
  38. instance.full_name+= ', ' + suf.__unicode__()
  39. print 'Saving As', instance.full_name
  40. instance.save()
Add Comment
Please, Sign In to add comment