【问题标题】:Django: Cannot insert user profile data from model into the templateDjango:无法将模型中的用户配置文件数据插入模板
【发布时间】: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


    【解决方案1】:

    现在个人资料中有许多记录,因为您有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}}
    

    【讨论】:

    • 如果我只想显示特定登录用户的配置文件数据怎么办?我必须更改我的模型/视图吗?
    • 见我已经更新了我的答案。看看并告诉我它是否适合你。
    • 如果解决方案对您有用。您可以投票并选择我的答案。感谢合作。
    • 我会尽快做。
    猜你喜欢
    • 2018-09-26
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2011-11-15
    • 1970-01-01
    相关资源
    最近更新 更多