OnetoOneField连接,无法访问相关信息,django

时间:2014-12-07 15:44:08

标签: python django

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='oser')
    picture = models.ImageField(upload_to='profile_images', blank=True)

所以,我已将图片添加到用户个人资料中,效果很好,但我无法访问图片以在用户个人资料中显示它

view.py:

def profile(request):
if request.user.is_authenticated():
    user = User.objects.get_by_natural_key(request.user.get_username())
    t = loader.get_template("profile.html")
    c = Context({'user2': user, })
    return HttpResponse(t.render(c))
else:
    raise Http404

我在django docs中找到了什么

class Employee(models.Model):
    user = models.OneToOneField(User)
    department = models.CharField(max_length=100)

u = User.objects.get(username='fsmith')
freds_department = u.employee.department

然而,这对我不起作用,我只是无法获得UserProfile.picture

u = User.objects.get(username= request.user.get_username())
s = u.UserProfile.picture

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您应该使用在外键字段中指定的“相关名称”来访问用户个人资料,而不是类名:

s = u.oser.picture

默认情况下,“related_name”与相关的模型类名相同,但为小写。您指定了related_name =“oser”。