Skip to content

django


custom django user

From the following tutorials: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model https://testdriven.io/blog/django-custom-user-model/ (Note: this must be done before the first migration).

Create a custom user model in one of your apps (MyApp):

from django.contrib.auth.models import AbstractUser
from django.db import models


# Create your models here.
class User(AbstractUser):
    #add any fields here that are not username, password, email, first_name, last_name
    contact_number = models.CharField("Property Address", max_length=250, blank=True)

    def __str__(self):
        return self.username

Change the default user model to your custom model in the settings.py

AUTH_USER_MODEL = "myapp.MyUser"

Create custom edit forms in forms.py:

from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from .models import User


class CustomUserCreationForm(UserCreationForm):

    class Meta:
        model = User
        fields = ("username","email", "full_name", "contact_number", )


class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = User
        fields = ("username","email", "full_name", "contact_number", )

In the same apps admin.py module register the user model. Registering a model in the admin.py allows for it to be editable in the admin pages.

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ["email", "username",]

admin.site.register(CustomUser, CustomUserAdmin)

Don't forget to add the app to the projects installed apps in settings.py:

INSTALLED_APPS = [
    'myapp.apps.PollsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

See also