1

私は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 %} 

答えて

2

あなたはget.objects.all()を持っだって多くのレコードは、今のプロファイルにがあります。そのように使用してください。 HTMLで今

profiles = Profile.get.objects.all() 

# for first profile's country 
country1 = profiles.0.country 

#for second profile entry 
country2 = profiles.1.country 

Alternatively in html

{% for profile in profiles %} 
    {{profile.country}} 
    {{profile.timezone}} 
{% endfor %} 

for a specific user, get the id of that user and then get their profile

id = request.user.pk 
profile = get_object_or_404(Profile, user__id=id) 

、私はログインしているユーザー固有のためのプロファイルデータを表示したい場合はどのような

{{profile.country}} 
{{profile.timezone}} 
+0

?モデル/ビューを変更する必要がありますか? – user3088202

+0

私の回答を更新しました。見て、それがあなたのために働くかどうか私に教えてください。 –

+0

それはうまくいった。どうもありがとうございました! – user3088202

関連する問題