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>

登录.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 %}

设置.py

AUTH_PROFILE_MODULE = "forums.UserProfile"

视图.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("/")
4

2 回答 2

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

    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
于 2013-03-29T05:28:19.000 回答
0

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

于 2013-03-29T05:56:34.387 回答