如何在包含的模板中获取用户配置文件?

时间:2013-03-29 05:23:47

标签: django

我可以使用用户在login.html中获取用户个人资料/ img吗?我想在我的所有页面中加载登录模块。什么是包含模板的最佳实践?

模型

class UserProfile(models.Model):
    User = models.ForeignKey(User, unique=True)
    ProfImg = models.FileField(upload_to='images')
    UserName = models.CharField(max_length=50)

def __unicode__(self):
    return self.UserName

base.html文件

<html>
<head>
<title>
</title>
</head>
<body>
{% include '/login.html' %}
</body>
</html>

的login.html

{% if user.is_authenticated %}
    <div class ="profile-info">
        <img src="{{ MEDIA_URL }}{{ request.user.get_profile.ProfImg }}" width = "150" height = "150"  />
        Welcome {{ request.user.get_profile.UserName }}               
       <p>You last logged in on Tuesday the 19th of March, 2013 at 01:32pm.</p>
       <p align="center"><a href="#">Profile</a> | <a href="#">Logout</a></p>
 {% else %}

settings.py

AUTH_PROFILE_MODULE = "forums.UserProfile"

view.py

def login_request(request):

     username = request.POST.get("username")
     password = request.POST.get("password")

     user = authenticate(username=username, password=password)
     if user is not None:
         login(request, user)
         return redirect("/")

2 个答案:

答案 0 :(得分:3)

  1. 用户必须为OneToOneField
  2. 请勿在字段名称中使用大写字母。这是一个不好的做法。您必须阅读PEP8(编码风格)。
  3. 请删除UserProfile模型中的UserName字段,因为它已在用户模型中定义。

    class UserProfile(models.Model):
        user = models.OneToOneField(User)
        profimg = models.FileField(upload_to='images')
    
        def __unicode__(self):
            return "{0}".format(self.user.username)
    
    {% if user.is_authenticated %}
    <div class ="profile-info">
        <img src="{{ user.userprofile.profimg.url }}" width = "150" height = "150"  />
        Welcome {{ user }}               
       <p>You last logged in on Tuesday the 19th of March, 2013 at 01:32pm.</p>
       <p align="center"><a href="#">Profile</a> | <a href="#">Logout</a></p>
    {% else %}
    ............
    {% endif %}
    
  4. 在模板使用中访问用户扩展信息

     {{ user.userprofile.field_name }} or {{ request.user.userprofile.field_name }}
    

    然后在你的观点中

     request.user.get_profile().field_name
    

答案 1 :(得分:0)

如果您正确设置了AUTH_PROFILE_MODULE,则可以使用user.get_profile.attribute