我正在为用户使用Django的默认身份验证,我创建了一个单独的模型来扩展用户配置文件。当我尝试访问未显示在页面上的用户个人资料信息时。在我看来,我将Profile对象传递给视图的上下文,但它仍然无效。
当我在shell中尝试它时,我得到 AttributeError:'QuerySet'对象没有属性'country' 我这样做时出错:
profile = Profile.get.objects.all()
country = profile.coutry
country
以下是我的models.py:
from pytz import common_timezones
from django.db import models
from django.contrib.auth.models import User
from django_countries.fields import CountryField
from django.db.models.signals import post_save
from django.dispatch import receiver
TIMEZONES = tuple(zip(common_timezones, common_timezones))
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
country = CountryField()
timeZone = models.CharField(max_length=50, choices=TIMEZONES, default='US/Eastern')
def __str__(self):
return "{0} - {1} ({2})".format(self.user.username, self.country, self.timeZone)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
这是我的views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from user.models import Profile
@login_required()
def home(request):
profile = Profile.objects.all()
return render(request, "user/home.html", {'profile': profile})
最后是home.html文件:
{% extends "base.html" %}
{% block title %}
Account Home for {{ user.username }}
{% endblock title %}
{% block content_auth %}
<h1 class="page-header">Welcome, {{ user.username }}. </h1>
<p>Below are you preferences:</p>
<ul>
<li>{{ profile.country }}</li>
<li>{{ profile.timeZone }}</li>
</ul>
{% endblock content_auth %}
答案 0 :(得分:2)
现在个人资料中有多条记录,因为您有get.objects.all()
。所以以这种方式使用它。
profiles = Profile.get.objects.all()
# for first profile's country
country1 = profiles.0.country
#for second profile entry
country2 = profiles.1.country
或者在html中
{% for profile in profiles %}
{{profile.country}}
{{profile.timezone}}
{% endfor %}
对于特定用户,获取该用户的
id
,然后获取他们的个人资料
id = request.user.pk
profile = get_object_or_404(Profile, user__id=id)
现在在html中,
{{profile.country}}
{{profile.timezone}}