验证成功后,从用户模型引用扩展变量

时间:2017-06-06 21:58:30

标签: python django authentication django-models static

因此,我使用一对一字段扩展了基本django用户模型:

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='user')
    user_avatar = models.ImageField(storage=site_media_upload_location, null=True, blank=True)

验证后,除用户模型中的user_avatar变量外,其他显示正确:

{% if request.user.is_authenticated %}
  <div class="user">
    <div class="user-image">
      <img class="img-responsive img-circle" src="{{ MEDIA_URL }}{{ request.user.userprofile.user_avatar.url }}" alt="User Avatar">
    </div>
    <div class="dropdown user-dropdown">
    Hello,
    <a href="#" aria-expanded="true">{{ request.user.first_name }}<i class="fa fa-caret-down" aria-hidden="true"></i></a>
    <ul class="sub-menu text-left">
      <li><a href="#">My Profile</a></li>
      <li><a href="#">Settings</a></li>
      <li><a href="#">Log Out</a></li>
    </ul>
  </div>
</div>
{% else %}
Do something else
{% endif %}

我的MEDIA_URL在settings.py文件中定义为

MEDIA_URL = "/site_media/"

这纯粹是每个&#34;用户&#34;将存储头像用于开发目的。

我尝试了几种组合,但似乎都没有效果:

<img class="img-responsive img-circle" src="{{ MEDIA_URL }}{{ request.user.userprofile.user_avatar.url }}" alt="User Avatar">

......而这......

<img class="img-responsive img-circle" src="{{ MEDIA_URL }}{{ request.userprofile.user_avatar.url }}" alt="User Avatar">

..而且......

<img class="img-responsive img-circle" src="{{ MEDIA_URL }}{{ request.user.user_avatar.url }}" alt="User Avatar">

如果有人知道如何在认证成功后引用扩展模型的变量,我将非常感激!

1 个答案:

答案 0 :(得分:0)

更改此行:

user = models.OneToOneField(User, related_name='user')

为:

user = models.OneToOneField(User, related_name='userprofile')

和此:

src="{{ MEDIA_URL }}{{ request.user.userprofile.user_avatar.url }}"

应该有用。

当您致电request.user时,该对象会尝试获取userprofile设置的属性related_name。您已将related_name设置为user,因此request.user没有属性userprofile