user3199840
user3199840

Reputation: 535

Extending Django default user

I'm trying to build a user profile which builds on the default Django user. I'm trying to extend the default user with an extra fields like this:

class MyMember(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL) #not sure about this
    birthday = models.DateField()

    USERNAME_FIELD = 'user'       #how to use username field from default user?           
    REQUIRED_FIELDS = ['birthday',]

    def __unicode__(self):
        return self.username

But I'm getting this error: 'Manager' object has no attribute 'get_by_natural_key'? Why? I would also like the USERNAME_FIELD to be the username from the default user. How?

Upvotes: 0

Views: 303

Answers (2)

aliteralmind
aliteralmind

Reputation: 20163

Here's the UserProfile model class I use to extend the User model in my demo website:

#Private function required by image field.
def _get_upload_file_name_w_sub_dir(instance, filename):
    return  "uploaded_files/{0}{1}_{2}".format("profile_pic/", (str(time()).replace(".", "_"), filename))

class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    # related_name is so you can reference *this* model as "user.profile"
    # instead of "user.userprofile"
    user = models.OneToOneField(User, related_name="profile")

    # The additional attributes we wish to include.
    year_discovered = models.IntegerField(blank=True,
        verbose_name="Year you discovered Billy Joel's music/became a fan")
    profile_picture = models.ImageField(upload_to=get_upload_profile_pic_file_name,
        blank=True, null=True)

    # Override the __unicode__() method to return out something meaningful!
    def __unicode__(self):
        return self.user.username

Here is the official documentation on extending the user model.

Upvotes: 1

Aaron Lelevier
Aaron Lelevier

Reputation: 20838

This is how you would extend the default Django User model. You would want to use a ForeignKey, and then you can use dot notation to access the fields of the User model.

Here:

from django.contrib.auth.models import User

class MyMember(models.Model):
    user = models.ForeignKey(User)
    birthday = models.DateField()

    def __unicode__(self):
        # the default "username" field in the django user model
        return self.user.username

Upvotes: 1

Related Questions