gkpo
gkpo

Reputation: 2672

Django - Attach data to model that will not be saved to the database

I need my django users to belong to an Office.

I did the following to extend the default user model:

class UserProfile(models.Model):
  user = models.OneToOneField(User)
  office = models.ForeignKey('Office')

My post_save signal for the user model calls this function:

def create_user_profile(sender, instance, created, **kwargs):  
  if created:
    profile = UserProfile.objects.create(
      user = instance,
      office = instance.office
    )

I basically want to attach office to "instance". Which means when I create the user I do the following:

user = User(
      office = office,
      username = username,
      email = email,
      password = password
    )

But I get the error:

'office' is an invalid keyword argument for this function

Which is normal because office is not a field for the User model. But is there a way to tell django to ignore this field, that this field is only here to "carry" information temporarily?

Upvotes: 0

Views: 41

Answers (1)

catavaran
catavaran

Reputation: 45575

Just set the office as a simple attribute:

user = User(username=username, email=email)
user.set_password(password)
user.office = office
user.save()

Upvotes: 1

Related Questions