question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Adding fields to the User model

See original GitHub issue

Please excuse me if the answer to my question is painfully obvious but I’m new to Django and I’m not very familiar with custom user models.

If I wanted to add another field to the user model (for example, “department” - the users are employees), where would I add it?

I figured I could add a department variable to models.py but it doesn’t seem to work. When I login to the admin site, I don’t see a “department” field when I add a user. Similarly, I don’t see a “name” field in the admin site - I only see First Name, Last Name, and Email Address.

# models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import

from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible


@python_2_unicode_compatible
class User(AbstractUser):

    # First Name and Last Name do not cover name patterns
    # around the globe.
    name = models.CharField(blank=True, max_length=255)
    department = models.CharField(blank=True, max_length=5)

    def __str__(self):
        return self.username

    def get_absolute_url(self):
        return reverse('users:detail', kwargs={'username': self.username})

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:26 (14 by maintainers)

github_iconTop GitHub Comments

5reactions
dezoitocommented, Jan 18, 2016

I hadn’t had any success with users/admin.py before, but the SO answer seems to be what was missing.

Overriding the fieldsets, however, is only working for the user change form. The user creation form remains unaffected - which is odd - but I can live with that.

Here’s what my users/admin.py is looking like, in case anyone needs a quick example (or can spot what is still missing):

# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as AuthUserAdmin
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
from .models import User


class MyUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = User

class MyUserCreationForm(UserCreationForm):

    error_message = UserCreationForm.error_messages.update({
        'duplicate_username': 'This username has already been taken.'
    })

    class Meta(UserCreationForm.Meta):
        model = User

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])


@admin.register(User)
class MyUserAdmin(AuthUserAdmin):
    form = MyUserChangeForm
    add_form = MyUserCreationForm
    fieldsets = AuthUserAdmin.fieldsets + (
            ('User Profile', {'fields': ('name',
                                        'location',
                                        'department',
                                        'phone',
                                        'extension')}),
    )
    list_display = ('username', 'name','location','department')
    search_fields = ['name']

Again, thank you for the help.

3reactions
dezoitocommented, May 18, 2018

From the Django 2.1 Release notes:

UserCreationForm and UserChangeForm no longer need to be rewritten for a custom user model.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Extending the User model with custom fields in Django
All you have to do is add AUTH_USER_MODEL to settings with path to custom user class, which extends either AbstractBaseUser (more customizable version)...
Read more >
How to add fields to the User model in Django
To add fields to your model that you want to share among all the users, just include them in the CustomUser model. For...
Read more >
Add Custom User Model (with custom fields like phone no ...
According to django documentation, you should create a custom user model whenver you start a django project. Because then you will have full ......
Read more >
Custom User model fields - Web Forefront
To support custom user models, Django offers the helper method get_user_model that returns a reference to whatever user model is defined in the...
Read more >
Customizing authentication in Django
contrib.auth.models.AbstractUser and add your custom profile fields, although we'd recommend a separate model as described in Specifying a custom user ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found