私はDjangoのデフォルト認証を使用しています。ユーザープロファイルを少し拡張するために別のモデルを作成しました。ユーザープロファイル情報にアクセスしようとすると、ページに表示されません。私の見解では、Profileオブジェクトをビューのコンテキストに渡しますが、まだ動作しません。Django:テンプレートからユーザープロファイルデータをモデルに挿入できません
私はシェルでそれをしようとすると、私ははAttributeErrorを得る:「クエリセット」オブジェクトは、私は何の属性「国の エラーがない:以下
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 %}
?モデル/ビューを変更する必要がありますか? – user3088202
私の回答を更新しました。見て、それがあなたのために働くかどうか私に教えてください。 –
それはうまくいった。どうもありがとうございました! – user3088202