Search code examples
djangodjango-modelsadmin

Django - list_display attribute not showing any fields for Model with OneToOne with User Model


So I have come an across something sort of weird. I just noticed that none of my fields that I want displayed on my admin page is not there. The failing model is a "Profile" model that is an extension to the User model, with a oneToOne relationship The code looks something like this.

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

# Create your models here.

#We need to extend the User Model
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.CharField(max_length=4096, null=True)
    email_confirmed = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username

    def get_username(self):
        return self.user.username

    def get_bio(self):
        return self.bio

    def get_email_confirmed(self):
        return self.email_confirmed

@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

admin.py

from django.contrib import admin
from .models import Profile

# Register your models here.

class ProfileAdmin(admin.ModelAdmin):
    list_display = ('email_confirmed', 'bio')

admin.site.register(Profile)

However, even with these changes, the admin page looks like this:

enter image description here


Solution

  • I haven't fully gone through as I don't have a working Django environment with me now. Just try this though. I had a similar code. Could be it.

    class ProfileAdmin(admin.ModelAdmin):
        list_display = ('email_confirmed', 'bio')
    
    admin.site.register(Profile,ProfileAdmin)