Brian
Brian

Reputation: 877

How to add a field in Django User Model?

I have three different types of users in my project. The three models have OneToOneField with the User model.

In many cases, I want to figure out which of the three type the user is. Is there a quick way to do that?

I'm thinking to add a field in User model but not sure how that can be done.

Upvotes: 1

Views: 1034

Answers (3)

jape
jape

Reputation: 2901

If you want to add a choice of what kind of user it is, I would try something like this: https://docs.djangoproject.com/en/1.8/ref/models/fields/#choices

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    )
    year_in_school = models.CharField(max_length=2,
                                      choices=YEAR_IN_SCHOOL_CHOICES,
                                      default=FRESHMAN)

    def is_upperclass(self):
        return self.year_in_school in (self.JUNIOR, self.SENIOR)

Upvotes: 0

Shaikhul
Shaikhul

Reputation: 712

You can implement the django.contrib.auth.models.User interface, take an example of django.contrib.auth.models.AnonymousUser which extends django.contrib.auth.models.User

https://docs.djangoproject.com/en/1.8/ref/contrib/auth/#django.contrib.auth.models.AnonymousUser

Upvotes: 0

Rahul Gupta
Rahul Gupta

Reputation: 47846

To extend the User model with your extra fields, you can use AbstractUser model. This will provide you with all the User fields like username, email and etc. Then, add all the extra fields in MyUser model.

You need to do something like:

models.py

from django.contrib.auth.models import AbstractUser

class MyUser(AbstractUser):
   my_extra_field = .. # your extra field

This will provide all the User fields along with the extra field named my_extra_field in MyUser model.

Upvotes: 1

Related Questions