Tag Archives: django-admin

Customizing you Django user admin with Inline sections

Screen Shot 2013-05-12 at 3.56.43 PM

I was using django-userena for user management on a django app. Userena is a django app that works with “django.contrib.auth.user” to provide additional features such activation, password resets over email and messaging in addition to signin and signups.

With Userena the django Auth admin site had a number of “Inline” management sections that incorporated the information coming in from the Userena app relevant to the particular user.

The sections were:
Username:Password
Personal Info
Permissions
Important Dates
Userena Registrations

I wanted to add my Custom profile to the Bottom of that list. My custom profile , otherwise also known as the one you set as the “AUTH_PROFILE_MODULE”

AUTH_PROFILE_MODULE = “accounts.MyCustomProfile”

How does one do that?

Well basically you want to extend the “custom” admin interface . The relevant django doc for all things ModelAdmin is located here.

My model which I want to add in: is

from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile


# Create your models here.

class MyCustomProfile(UserenaBaseProfile):
    """The Userena User profile"""
    user = models.OneToOneField(User,
        unique=True,
        verbose_name=_('user'),
        related_name='my_profile')
    bio = models.CharField(max_length=1000,default="",blank=True)
    # Make this field not editable because it controls access to uid from legacy db
    my_legacy_user_object = models.SmallIntegerField(null=True,editable=False,unique=True)

    def __unicode__(self):
        return self.bio

To accomplish the inline display of this model along with the rest of the stuff userena already put into the admin page for the user I had to add this as my admin.py for the accounts app.

__author__ = 'hari'
from django.contrib import admin
from .models import MyCustomProfile
from userena.utils import get_user_model,get_profile_model
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from userena.admin import UserenaAdmin,UserenaSignupInline

class MyCustomProfileAdmin(admin.ModelAdmin):
    list_display = ["user" ,"bio","my_legacy_user_object"]
    search_fields = ["user__first_name","user__last_name","my_legacy_user_object"]

#docs from https://github.com/bread-and-pepper/django-userena/blob/master/docs/faq.rst
admin.site.unregister(get_profile_model())
admin.site.register(MyCustomProfile,MyCustomProfileAdmin)

class MyCustomProfileAdminInline(admin.StackedInline):
    model = MyCustomProfile


class MyCustomProfileAddedAdmin(UserenaAdmin):
    inlines = [UserenaSignupInline,MyCustomProfileAdminInline]

admin.site.unregister(get_user_model())
admin.site.register(get_user_model(),MyCustomProfileAddedAdmin)

The result is what we get nicely here