Codementor Events

Django-admin User creation on Custom user model

Published Jul 05, 2019

When using the Django's default authentication model (django.contrib.auth.models.User), The Django admin page has a separate workflow for creating the user object. The admin is first asked only for the username and password of the new user. Once the details are provided, the user is created (with hashed password) and other fields can be added for the user as an edit.

But when the AUTH_USER_MODEL is a custom user model, then all these powers are lost in the admin panel and you are not able to create users or change their passwords using the admin panel as the passwords are not hashed by default in this case.

How to fix this and create users from the admin panel? Just a simple trick.

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

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

admin.site.register(models.MyUser, UserAdmin)

In the above code, we just registered our User model to use the UserAdmin class, which has the configurations for the add and edit forms.

If you now go to the admin panel and click on Add User, you should see a different form with only username and password.

Screenshot 2019-07-05 at 1.03.28 PM.png

And when you go to the edit user form, you should see that password is not a text field now, but a label containing the hash, salt, e.t.c. You will also have a link below to change the user's password.

Screenshot 2019-07-05 at 1.22.05 PM.png

After this change, you need not go to the shell to create new users into your application everytime.

Discover and read more posts from Aswin Murugesh
get started
post comments2Replies
Dream Team
2 years ago

Thank you very much for this script… Very grateful

Edwin Marin Acevedo
4 years ago

Excellent contribution, just what I needed