Reputation: 121
I keep getting this error, I can't seem to fix it. Each time a new user signs up, he/she can create a profile. I can create and edit a profile, but I can't view the profile. Maybe my code is wrong, but idk. I am fairly inexperienced.
TypeError at /profile/1/
'Profile' object is not iterable
Url:
url(r'^profile/(?P<pk>\d+)/$', views.profile, name='profile')
View:
@login_required
def profile(request, pk):
prof = get_object_or_404(Profile, pk=pk)
return render(request, 'blog/profile_detail.html', {'prof': prof})
Model:
class Profile(models.Model):
user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='prof')
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(blank=True, null=True)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
HTML:
{% for pro in prof %}
<a href="{% url 'profile_edit' pk=prof.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
<h2>{{ user.username }}</h2>
<p>{{ user.profile.bio }}</p>
<p>{{ user.profile.location }}</p>
<p>{{ user.profile.birth_date }}</p>
{% empty %}
<a href="{% url 'profile_new' pk=prof.pk %}"><span class="gliphicon gliphicon-plus"></span></a>
{% endfor %}
If I am supplying too little information, please say so nicely, no nasty comments and down-votes please. Please help a noob.
Upvotes: 2
Views: 2023
Reputation:
You are only passing a single object prof
in the context to the template but are iterating over an iterable.
You need to replace {% for pro in prof %}
with {% if prof %}
in your template.
Upvotes: 2