How to get user's last login with OneToOneField and display it on admin panel?

Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/rustem/studypageback/venv/lib/python3.6/site-packages/django/core/management/base.py", line 436, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'portal_users.admin.ProfileAdmin'>: (admin.E108) The value of 'list_display[10]' refers to 'user__last_login', which is not a callable, an attribute of 'ProfileAdmin', or an attribute or method on 'portal_users.Profile'. System check identified 1 issue (0 silenced).

There is my code

models.py:

class Profile(models.Model): user = models.OneToOneField( User, null=True, related_name='profile', on_delete=CUSTOM_SET_NULL, ) student_id = models.IntegerField( blank=True, null=True, verbose_name='ID студента/преподавателя', help_text='Из 1С', )

first_name = models.CharField(
    max_length=200,
    verbose_name='Имя',
    blank=True,
)
last_name = models.CharField(
    max_length=200,
    verbose_name='Фамилия',
    blank=True,
)

admin.py:

@admin.register(models.Profile) class ProfileAdmin(admin.ModelAdmin):

list_display = [
    'user',
    'first_name',
    'last_name',
    'user__last_login',
]

You would need to add a custom method that would display the last login on admin:

class ProfileAdmin(admin.ModelAdmin):
    list_display = ['user','first_name', 'last_name', 'get_last_login']
    
    def get_last_login(self,instance):
        return instance.user.last_login
    get_last_login.short_description = "Last login"

More on this: Documentation on list_display

Back to Top