1

사용자를 위해 장고의 기본 인증을 사용하고 있으며 사용자 프로필을 약간 확장하기 위해 별도의 모델을 만들었습니다. 사용자 프로필 정보에 액세스하려고 시도 할 때 페이지에 표시되지 않습니다. 필자는 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을 파일 : 당신이 get.objects.all()이 사촌

{% 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

가, 지금은 프로필에 많은 레코드있다. 그래서 그렇게 사용하십시오. 이제 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

관련 문제