Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.5 + User model relationship

Django 1.5+ allows us to add custom fields to a User. I want to use this fact, but I don't necessarily know what is good practice. Here is a situation I am confused on how to handle the models.

Given the option to add fields to User, if a project only has one type of User, lets say a Student model, can I simply add student-specific fields to User? I am new to Django, but I believe the alternative would be to set up general User settings, and create a Student model, and a one-to-one unique field in it call user.

Should you ever expand a Django User's fields to mimic that of a model, even if the project is guaranteed only to have one type of user?

like image 837
Joker Avatar asked Jun 02 '13 06:06

Joker


1 Answers

If you only have one type of user and are using Django 1.5+, I would recommend taking advantage of the new AbstractUser. Extending Django's default user

As an example where you want to add date of birth and favorite color:

#myusers/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models

class MyUser(AbstractUser):
    dob = models.DateField()
    favorite_color = models.CharField(max_length=32, default='Blue')

If you need more flexibility you can extend the AbstractBaseUser instead of AbstractUser, but for most basic cases you should only need AbstractUser.

Also note that in either case, you'll need to reference your user model by using settings.AUTH_USER_MODEL.

Using out example above and assuming the app it was defined in is called myusers:

#settings.py
AUTH_USER_MODEL = 'myusers.MyUser'

The method you mention of creating a Student model with a one-to-one field to the User model still works, but is not as clean (there are still cases where it makes sense if you have multiple kinds of users).

I don't normally like to reference books in answers, but I found that Two Scoops of Django's, Chapter 16 on the User model gave a much clearer explanation of where the different options are appropriate than the current version of the online Django docs. The book is overall a very useful intro to Django and was written based on 1.5. You'd have to buy the book or find someone who has it, though... (FYI: I don't get any money recommending this).

You could also take a look at this SO question/answer: https://stackoverflow.com/a/14104748/307293

like image 197
Jacinda Avatar answered Nov 15 '22 03:11

Jacinda