Home > database >  How to get data from User related model to template
How to get data from User related model to template

Time:11-21

I have Profile model in addition to native User model. Since user is logged in, I need to load avatar image to all pages in frontend. I need something like this:

{% if request.user.is_authenticated %}<img src={{ profile.avatar }}>{% endif %}

How I can do that?

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    avatar = models.ImageField(upload_to='media/avatar/', verbose_name='Аватар',
                           default='media/avatar/default_avatar.jpg')

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

CodePudding user response:

First set the related_name of user field:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
    avatar = models.ImageField(upload_to='media/avatar/', verbose_name='Аватар', default='media/avatar/default_avatar.jpg')

Then you can write:

{% if request.user.is_authenticated %}<img src={{ request.user.profile.avatar }}>{% endif %}

To display the avatar in all templates, you can define a base template from which all others inherit, look at the documentation for details.

  • Related