Wednesday, June 7, 2017

Extending the user model and accessing fields in template context

Have failed to find an easy answer to this so will lazily ask the broader community before I retire tonight ;-).

I have a model that I use to extend the User model like yo:

from django.contrib.auth.models import User

class Dude(models.Model):
    nickname = models.CharField('Nickname', max_length=MAX_NAME_LENGTH)
    clans = models.ManyToManyField('League', blank=True, related_name='dudes_in_clan')
    user = models.OneToOneField(User, related_name='dude', blank=True, null=True, default=None)

Now  {{ user }} renders as the user name quite well in my templates so I can show the logged in user in a header. Nice.

But I'd like to access fields in the extended model like {{ user.dude.nickname }}.

Alas, it's not that simple clearly. I'm missing something, as that renders blank.

The Django Toolbar is not very helpful in drilling down as it only lists:

'user': <SimpleLazyObject: <User: me>>

and reveals nothing about the . notation elements of user that I might be able to access. I can access all the fields  of the User model like {{ user.date_joined }} works fine. But the related_name of the OneToOne relationship isn't working as I'd have hoped.

Is there a trick I'm missing?

Regards,

Bernd.



No comments:

Post a Comment