1

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

我不断收到此错误'User' object has no attribute 'MyProfile'

模型.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")

管理员.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)
4

1 回答 1

0

试试这个:

def get_dealer_num(self, obj):
        return MyProfile.objects.get(user=obj).dealer_num
于 2019-03-07T21:13:15.353 回答