简体   繁体   中英

Extending Django User Model and Adding to Admin List Display

I am trying to extend my user model with a profile and then add the new profile fields to the user list display so that it is searchable. Everything is working up until adding it to the admin list display.

I keep getting this error 'User' object has no attribute 'MyProfile'

models.py

from django.db import models

# Create your models here.
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile

class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,
                                unique=True,
                                verbose_name=_('user'),
                                related_name='my_profile')
    dealer_num = models.CharField(blank=True,
                                max_length=15,
                                verbose_name="Dealer Number")

Admin.py

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

from .models import MyProfile

class ProfileInline(admin.StackedInline):
    model = MyProfile
    can_delete = False
    verbose_name_plural = 'Profile'
    fk_name = 'user'
    fields = ('user', 'dealer_num')

class UserAdmin(UserAdmin):
    inlines = (ProfileInline, )
    list_display = ('username', 'get_dealer_num')


    def get_inline_instances(self, request, obj=None):
        if not obj:
            return list()
        return super(UserAdmin, self).get_inline_instances(request, obj)
    def get_dealer_num(self, obj):
        return obj.MyProfile.dealer_num


admin.site.unregister(User)
admin.site.register(User, UserAdmin)

Try this:

def get_dealer_num(self, obj):
        return MyProfile.objects.get(user=obj).dealer_num

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM