2013-03-29 52 views
0

我可以使用用户在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("/") 

回答

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

要访问用户扩展的信息模板使用

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

然后在你的看法

request.user.get_profile().field_name 
+1

我试过你的代码但它没有任何回报。我也试过'',但结果相同 – unice

+0

您需要修复您的代码 – catherine

+0

感谢您的更正。我会尝试你所说的。我稍后会回来看看结果。 – unice

0

如果您在AUTH_PROFILE_MODULE正确设置,您可以使用user.get_profile 。属性

+0

我试过{{user.get_profile.ProfImg}},但它给我一个错误“无法解析关键字'用户'进入字段。选择是:ProfImg,用户名 – unice

+0

你能显示更多的代码吗?我认为你没有用户在功能范围内,请尝试request.user – dusual

+0

没有错误但没有返回任何内容我更新了我的问题中的代码用户名返回当我仅使用{{user}} – unice

相关问题