简体   繁体   中英

Creating a new instance of a Custom User Model in Django

I have a model which is an extension of a User model in Django 1.8. I am also connecting to a MySQL database for this.

class LibraryUser(models.Model):
  user_id = models.OneToOneField(User)
  is_catalogue_subscriber = models.BooleanField(default=True)
  is_research_subscriber = models.BooleanField(default=True)
  library_membership_number = models.CharField(max_length=64)

The reason why I extended the User model, of course is to use the authentication framework.

So now, I want to create a new LibraryUser using the library_membership_number as the login username. How should I do so? Do I create the User first then reference the LibraryUser ?

ie given some_ variables either received by a POST or by migration of users to the new table

u = User.objects.create_user(email=some_email, password=some_password)
lu = LibraryUser(library_membership_number, user_id = u.id)
lu.save()

Or is there a correct way to do this? Tried finding online but can't find something to particularly address this problem.

You should assign value to the specify fields as the following:

lu = LibraryUser(library_membership_number= '...', user_id = user)
lu.save()
  • library_membership_number

    You can't just assign a variable to library_membership_number . model is a object containing the fields. You should appoint the field and assign it: library_membership_number= '...' , or model can't parse which field you will store.

  • user_id

    It has defined foreignkey in advance. It can accept another model object to store: user_id = user . Don't call attribute of the user to store in LibraryUser .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM