Archive for the ‘Django’ Category

How to extend user model in Django and enable new fields in ‘newforms-admin’

Monday, August 18th, 2008

The way to specify admin interface options has changed in the recent development version of Django. An inline edited objects are now specified in a new way. Now you need to mention the link in an admin objects of both models participating in the relation.

So the question arises: how to make UserProfile to appear inline in the User editing interface in admin?

The solution is to import UserAdmin class and add an InlineAdmin objet to the inlines list. But there is a simple trick: you need to unregister and then register an AdminModel class for a User model. Here is an example.

models.py

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

class UserProfile(models.Model):
    website_url = models.URLField(verify_exists=False)
    user = models.ForeignKey(User, unique=True)

admin.py

from django.contrib import admin
from someapp.models import *
from django.contrib.auth.admin import UserAdmin

# Define an inline admin descriptor for UserProfile model
class UserProfileInline(admin.TabularInline):
    model = UserProfile
    fk_name = 'user'
    max_num = 1

# Define a new UserAdmin class
class MyUserAdmin(UserAdmin):
    inlines = [UserProfileInline, ]

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)