I have a model with foreignkeys. For this model I want to set the 'def str' as the user.
I have done this
from django.contrib.auth import get_user_model
User = get_user_model()
class Rosters(models.Model):
place = models.ForeignKey('Places')
position = models.ForeignKey('Positions', blank=True, null=True)
user = models.ForeignKey(User, related_name='roster')
validfrom = models.DateTimeField(blank=True, null=True)
validto = models.DateTimeField(blank=True, null=True)
def __str__(self):
return self.user
This will fetch username and show in admin pages. But when I try to create a new Roster. I get a TypeError __str__ returned non-string (type User)
I can remove the 'def str...' and create a Roster with no problem. But each Roster shows as Object in admin pages. So I can add back the 'def str..' to see the usernames of each roster.
I want them to always display as usernames. And I can't figure out why it's not working when I'm adding rosters.
You need to refer to the specific field within 'User' you want to display. Try:
def __str__(self):
return self.user.username
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With