I’m extending the UserProfile but I’m having trouble getting the new field – current_article – that I added to list_display to show properly in the user overview page –
Home › Auth › Users
The new fields has it’s own column but always with value (None) even after selecting values in the user detail page.
How can I get the field’s values to show up in overview admin page?
I referenced this stackoverflow question:
Django Admin: how to display fields from two different models in same view?
Here is the code:
#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)
And in 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)
Your method is actually raising an
AttributeErrorexception, but Django hides this when processinglist_display(It catches all exceptions and returnsNoneas the value).You need to have
return instance.get_profile().current_article.