Reputation: 3124
I am using Django's default auth for users and I have created a separate model to extend the user profile a bit. When I try to access the user profile info its not showing up on the page. In my view, I pass the Profile objects to the view's context but it still not working.
When I try it in the shell, I get AttributeError: 'QuerySet' object has no attribute 'country' error when I do:
profile = Profile.get.objects.all()
country = profile.coutry
country
Below is my 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()
Here is my 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})
And finally the home.html file:
{% 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 %}
Upvotes: 1
Views: 589
Reputation: 13047
There are many records in profile now, coz you have get.objects.all()
. so use it in that way.
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)
Now in html,
{{profile.country}}
{{profile.timezone}}
Upvotes: 2