[Answered ]-Guidance on creating Custom User Models in Django

2👍

First of all, your custom user model looks fine to me from first glance.

To properly integrate the custom model with the Django admin, you should replace the is_admin field to two fields which are used by Django admin is_staff and is_superuser. For more details see the documentation here. This will prevent non-staff (not admin) users from accessing the admin, as well as allow you to define a superuser to grant full access to.

EDIT: simpler method found, simply subclass AbstractUser and not AbstractBaseUser, this is detailed here. Here is your code, modified and cleared of any redundant fields (that are already implemented in the parent class)

class MyUser(AbstractUser):
    birthday = models.DateField(null=True, blank=True)
    city = models.CharField(max_length=50, blank=True)
    state = models.CharField(max_length=50, blank=True)

    user_title = models.CharField(max_length=254, blank=True)
    user_points = models.IntegerField(null=False, blank=True)
    avatar = models.FileField()

Now, to finish the process you only need to write the urls and views for your pages, and use the @login_required decorator where appropriate, to prevent “anonymous” users from accessing those pages.

Example view that implements the @login_required decorator:

from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required
def user_profile(request):
    # render your template with the RequestContext
    return render('profile.html')

Leave a comment