I'm trying to create an app that allows my user to create a House and then be able to add Occupants.
However my issue is that name of the house needs to be unique, SO far it saves the name as Auth.user, how do i get their username and then save that along with house. So for example "Jonsmith House"
this is what i have so far
User = settings.AUTH_USER_MODEL
class House(models.Model):
owner = models.ForeignKey(User, null=True, blank=True)
name = models.CharField(max_length=50)
def save(self, *args, **kwargs):
self.name = User
super(House, self).save(*args, **kwargs)
def __unicode__(self):
return smart_text(self.name)
class Occupant(models.Model):
house = models.ForeignKey(House)
occupants = models.ForeignKey(User)
I hope this make sense, thanks
From what I understand, you need an app for that allows your user to create a House and then be able to add Occupants.
Also your house name should be the one with your user(who created it) + "House".
Then something like this should suffice.
class House(models.Model):
# name of the house
name = models.CharField(max_length=20, null=True, blank=True)
owner = models.OneToOneField(User, null=True, blank=True)
Since, you only need single user as house owner and each house has a single owner, you need to make the relation OneToOne. If you need to refer your hour as you mentioned, (along with username of owner), override save method,
def save(self, *args, **kwargs):
self.name = "%s House" % (self.owner.username)
super(House, self).save(*args, **kwargs)
Now, for an occupant, each user may be an occupant of a house, but only of one, I suppose.
class Occupant(models.Model):
house = models.ForeignKey(House, null=True, blank=True)
user = models.ForeignKey(User, null=True, blank=True)
name = models.CharField(max_length=32, null=True, blank=True)