2012-08-06 61 views
0

我在擴展UserProfile,但我無法獲取新字段 - current_article - 我添加到list_display以在用戶中正確顯示概覽頁面 - Home › Auth › Users擴展django UserProfile,添加到list_display後,新字段顯示爲(無)

即使在用戶詳細信息頁面中選擇了值之後,新字段也有自己的列,但始終值爲(None)

如何獲取字段的值以顯示在概覽管理頁面中?

我引用這個計算器的問題: Django Admin: how to display fields from two different models in same view?

下面是代碼:

#admin.py 
class UserProfileInline(admin.StackedInline): 
     model = UserProfile 

    class CustomUserAdmin(UserAdmin): 
    inlines = [ 
       UserProfileInline, 
       ] 
    def current_article(self,instance): 
     return instance.user.current_article 

    list_display = ('id','username','email','current_article','first_name','last_name','is_active', 'date_joined', 'is_staff','last_login','password') 

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

而且在Models.py

#models.py 
from django.db import models 
from django.contrib.auth.models import User 
from django.db.models.signals import post_save 

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    current_article = models.ForeignKey(Article,blank=True,default=1) 

    def __unicode__(self): 
     return "{}".format(self.user) 


def create_user_profile(sender, instance, created, **kwargs): 
    if created: 
     UserProfile.objects.create(user=instance) 

post_save.connect(create_user_profile, sender=User) 

回答

2

你的方法實際上是提高了AttributeError例外,但Django在處理list_display時隱藏了它(它捕獲所有異常並返回None作爲值)。您需要有return instance.get_profile().current_article

+0

實際上是這樣!感謝您指出正在引發AttributeError。 – wintour 2012-08-06 20:59:24

+0

@Chris Patt。 Django沒有捕獲所有異常。唯一例外是AttributeError和ObjectDoesNotExist(請參閱https://github.com/django/django/blob/master/django/contrib/admin/templatetags/admin_list.py#L185)。所有其他例外均正常提出。 – thikonom 2012-08-23 21:42:16

相關問題