python - Django: Cannot insert user profile data from model into the template -
i using django's default auth users , have created separate model extend user profile bit. when try access user profile info not showing on page. in view, pass profile objects view's context still not working.
when try in shell, attributeerror: 'queryset' object has no attribute 'country' error when do:
profile = profile.get.objects.all() country = profile.coutry country
below models.py:
from pytz import common_timezones django.db import models django.contrib.auth.models import user django_countries.fields import countryfield django.db.models.signals import post_save 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 views.py
from django.shortcuts import render django.contrib.auth.decorators import login_required user.models import profile @login_required() def home(request): profile = profile.objects.all() return render(request, "user/home.html", {'profile': profile})
and home.html file:
{% extends "base.html" %} {% block title %} account home {{ user.username }} {% endblock title %} {% block content_auth %} <h1 class="page-header">welcome, {{ user.username }}. </h1> <p>below preferences:</p> <ul> <li>{{ profile.country }}</li> <li>{{ profile.timezone }}</li> </ul> {% endblock content_auth %}
there many records in profile now, coz have get.objects.all()
. use in way.
profiles = profile.get.objects.all() # first profile's country country1 = profiles.0.country #for second profile entry country2 = profiles.1.country
alternatively in html
{% profile in profiles %} {{profile.country}} {{profile.timezone}} {% endfor %}
for specific user,
id
of user , profile
id = request.user.pk profile = get_object_or_404(profile, user__id=id)
now in html,
{{profile.country}} {{profile.timezone}}
Comments
Post a Comment