从Django模板中的模型显示用户的特征

时间:2019-12-07 08:32:33

标签: python django django-models django-templates django-views

我想在模板中显示用户的用户特征。

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})

温度:

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

1 个答案:

答案 0 :(得分:1)

您可以使用:

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

在Django的User模型与Profile模型之间存在一对一的关系。