Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return self.user as foreignkey

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.

like image 216
sumpen Avatar asked Dec 08 '25 06:12

sumpen


1 Answers

You need to refer to the specific field within 'User' you want to display. Try:

def __str__(self):
    return self.user.username
like image 134
cbuch1800 Avatar answered Dec 09 '25 19:12

cbuch1800



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!