我可以使用用户在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("/")
答案 0 :(得分:3)
OneToOneField
请删除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 :(得分:0)
如果您正确设置了AUTH_PROFILE_MODULE,则可以使用user.get_profile.attribute