Donovan Keating
Donovan Keating

Reputation: 1885

Django: Get User first_name

I can't figure out how to return the string representation of the User object's first_name and last_name fields. The User is built into Django's from django.contrib.auth import get_user_model. I want a table UserDetails containing extra info on the user so I want the Django admin to display the name of the user the details belong to.

def __str__(self):
    return str(self.User.first_name) + ' ' + str(self.User.last_name)

This is what I did but it is being presented as:

I've tried changing model representations in Django admin before. User seems to behave differently though.

Upvotes: 0

Views: 2579

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

Instead of User it should be model's field name, e.g. if your field named user you can do this:

class SomeData(models.Model):
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)

    def __str__(self):
        return self.user.first_name + ' ' + self.user.last_name

Upvotes: 3

Related Questions