Reputation: 849
I want to display first name and last name. To achieve that, I have used __str__()
method. But it is not working.
class OnlineUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return f"{self.user.first_name} {self.user.last_name}"
Instead it display, user ID.
In admin.py
,
class OnlineUsersAdmin(admin.ModelAdmin):
# a list of displayed columns name.
list_display=['user']
admin.site.register(OnlineUsers, OnlineUsersAdmin)
Where I'm doing wrong? How to get the format I want?
Version:
Django==2.0.1
Debug:
user_info=OnlineUsers.objects.get_or_create(user=self.user)
print(user_info.__str__())
Output:
((<OnlineUsers: FIRST_NAME LAST_NAME >, False))
Upvotes: 3
Views: 2590
Reputation: 121
Here, inside return you can return only str + str, not str + int. So, you have to convert every int to str
from django.db import models
# Create your models here.
class Fabonacci(models.Model):
numstr = models.IntegerField()
terms = models.CharField(max_length=500)
def __str__(self):
return "The first " + str(self.numstr) + " terms in fibonacci series : " + self.terms
Upvotes: 0
Reputation: 88659
The list_display
--(Django doc) support callable methods too. So, define a user(...)
method on Model admin as,
class OnlineUsersAdmin(admin.ModelAdmin):
# a list of displayed columns name.
list_display = ['user']
def user(self, instance):
return instance.__str__()
Upvotes: 1
Reputation: 47374
You should use __str__
instead of user in list_display:
list_display=['__str__']
Otherwise you tell django to show user
field. And since User
model doen't have overrided __str__
method you see user's id.
Also you can just remove list_display
attribute. In this case __str__
will be used by default.
Upvotes: 3