Display user`s protrait from model in template in django

1880 views python
10

I want to display the the user protrait of the user in the templates.

models.py

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date_of_birth = models.DateField(blank=True, null=True)
    photo = models.ImageField(upload_to='user/%Y/%m/%d/', blank=True)

views.py

@login_required
def dashboard(request):
    # Display all actions by default
    actions = Action.objects.exclude(user=request.user)
    following_ids = request.user.following.values_list('id',
                                                       flat=True)
    if following_ids:
        # If user is following others, retrieve only their actions
        actions = actions.filter(user_id__in=following_ids)
    actions = actions.select_related('user', 'user__profile')\
                     .prefetch_related('target')[:10]

    return render(request,
                  'account/dashboard.html',
                  {'section': 'dashboard',
                   'actions': actions})

tempate:

 <img src="{{ Profile.photo.url }} " height="40" width="40"/>

answered question

you want to show the image of logged in user?

1 Answer

3

You can use:

<img src="{{ request.user.profile.photo.url }} " height="40" width="40"/>

as you have a One-to-One relationship between the django's User model and your Profile model.

posted this

Have an answer?

JD

Please login first before posting an answer.