我不断收到此错误,但似乎无法修复它。每次新用户注册时,他/她都可以创建个人资料。我可以创建和编辑个人资料,但无法查看该个人资料。也许我的代码是错误的,但我不知道。我相当缺乏经验。
TypeError at /profile/1/
'Profile' object is not iterable
网址:
url(r'^profile/(?P<pk>\d+)/$', views.profile, name='profile')
查看:
@login_required
def profile(request, pk):
prof = get_object_or_404(Profile, pk=pk)
return render(request, 'blog/profile_detail.html', {'prof': prof})
型号:
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 %}
如果我提供的信息太少,请说得好听,不要发表恶意评论和反对票。请帮助菜鸟。
最佳答案
您仅将上下文中的单个对象 prof
传递给模板,但正在迭代可迭代对象。
您需要在模板中将 {% for pro in prof %}
替换为 {% if prof %}
。
关于python - TypeError 'Profile' 对象不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50680951/