Wednesday, June 7, 2017

Re: Extending the user model and accessing fields in template context

On Thursday 08 June 2017 08:46:38 Bernd Wechner wrote:

> 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.

 

If there is no profile, an exception is thrown. It throws a rather useless exception RelatedObjectDoesNotExist, cause to catch it, you'd have to reference the accessor, which will throw RelatedObjectDoesNotExist and to catch it ... etc.

 

You can however catch it as an AttributeError, then inspect it's type. See: django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor

 

In templates exceptions are caught and silenced and the empty string is returned.

 

So to prevent a disconnect between a User model and a profile model, you basically have to make sure, that whenever a new User is created, you create a new profile. This is why typically, all fields in a profile model have null=True, so that you can listen to the post_save signal on the User model and create a profile, without requiring profile information.

 

It's either that, or you have to augment the things in your project that create users with the required profile data. By default that is the admin and the createsuperuser command.

--

Melvyn Sopacua

No comments:

Post a Comment