【发布时间】:2018-02-21 12:37:09
【问题描述】:
我正在为用户使用 Django 的默认身份验证,并且我创建了一个单独的模型来稍微扩展用户配置文件。当我尝试访问用户个人资料信息时,它没有显示在页面上。在我看来,我将 Profile 对象传递给视图的上下文,但它仍然无法正常工作。
当我在 shell 中尝试时,我得到 AttributeError: 'QuerySet' object has no attribute '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()
这是我的意见.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 %}
【问题讨论】:
标签: python django django-models django-templates django-views