简体   繁体   中英

Correct usage of django AbstractBaseUser class

I'm trying to move beyond tutorial-level knowledge and create my own user class by extending the AbstractBaseUser meta class, but I am having trouble finding an example that actually shows how to interact with this type of model via the API. Here's my model:

from __future__ import unicode_literals
from django.db import models
from django.utils.translation import ugettext as _

class Country(models.Model):
    iso3166 = models.CharField(_("country ISO 3166"), max_length=3, default="840", primary_key=True)
    name = models.CharField(_("country name"), max_length=40, default="USA")

    def __unicode__(self):
        return self.name

class MyUser(AbstractBaseUser):
    postal_code = models.CharField(_("zip code"), max_length=5, blank=True, default='')
    country = models.ForeignKey(Country)REQUIRED_FIELDS = ['country']

And here I am trying to interact with it via the shell:

from myapp.models import MyUser, Country
from django.utils.translation import ugettext as _
c = Country(iso3166="840",name=_("United States of America"))
c.save()
q = Country.objects.get(iso3166="840")
g = MyUser(username="bob",password="pass1",first_name="Robert",last_name="Smith",email="bob@here.net",country=q)

Which works fine up until the line where I define g, whence I get an error:

TypeError: 'username' is an invalid keyword argument for this function

I get what the error is saying and don't mind it, but I'm not sure what the correct syntax is for creating a new MyUser object.

AbstractBaseUser doesn't define any fields of its own (apart from password and last_login). So you can only pass in the fields you have defined in your subclass: postal_code and country.

In practice, this is very rarely useful; you probably want to subclass AbstractUser instead, which does define username and email fields among others.

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