扩展Django用户模型并添加到管理员列表显示

时间:2019-03-07 20:41:36

标签: python django django-admin django-userena

我试图用配置文件扩展用户模型,然后将新的配置文件字段添加到用户列表显示中,以便可以搜索。一切正常,直到将其添加到管理列表显示中。

我不断收到此错误'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)

1 个答案:

答案 0 :(得分:0)

尝试一下:

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