开发者

How to implement admin meta fields in Django 1.3 User profile?

开发者 https://www.devze.com 2023-04-03 09:19 出处:网络
from django.db import models from django.contrib.auth.models import User class MySiteProfile(models.Model):
from django.db import models
from django.contrib.auth.models import User

class MySiteProfile(models.Model):
    # This is the only required field
    user = models.ForeignKey(User, unique=True)

    # The rest is completely up to you.开发者_高级运维..
    favorite_band = models.CharField(max_length=100, blank=True)
    favorite_cheese = models.CharField(max_length=100, blank=True)
    lucky_number = models.IntegerField()

The problem is that User._meta.admin and MySiteProfile._meta.admin both return NoneType. I've dropped and recreated whole database, but no new fields appeared in admin panel; AUTH_PROFILE_MODULE is set.


There are a few ways you can make your MySiteProfile show up in the admin. One is to simply register your model with the admin, and it will show up under the app name it resides in.

Another is to unregister the contrib user from admin and instead load yours:

#admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_app.models import MySiteProfile

class MySiteProfileAdmin(UserAdmin):
  def __init__(self,*args,**kwargs):
    super(MySiteProfileAdmin).__init__(*args,**kwargs)
    fields = list(UserAdmin.fieldsets[0][1]['fields'])
    fields.append('favorite_band')
    fields.append('favorite_cheese')
    fields.append('lucky_number')
    UserAdmin.fieldsets[0][1]['fields']=fields

admin.site.unregister(User)
admin.site.register(MySiteProfile, MySiteProfileAdmin)

There are quite a few articles around on this topic, but hope that helps you out.

0

精彩评论

暂无评论...
验证码 换一张
取 消