当我在上下文中传递instance1
时,它给出了错误'User' object is not iterable
。我想在pk
的模板中显示“名称”。示例http://localhost:8000/users/15/profile-update/
pk=15
def userProfileUpdate(request, pk):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=User.objects.get(id=pk))
p_form = UserProfileForm(request.POST,
request.FILES,
instance=UserProfile.objects.get(user_id=pk))
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, 'Profile Updated!!!')
return redirect('users')
else:
instance1 = User.objects.get(id=pk)
u_form = UserUpdateForm(instance=User.objects.get(id=pk))
p_form = UserProfileForm(instance=UserProfile.objects.get(user_id=pk))
context ={
'object': instance1, # This is giving the error
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/userprofile.html', context)
TypeError at /users/15/profile-update/
'User' object is not iterable
Request Method: GET
Request URL: http://localhost:8000/users/15/profile-update/
Django Version: 2.1.4
Exception Type: TypeError
Exception Value:
'User' object is not iterable
Exception Location: /home/codism-7/.local/share/virtualenvs/django-njoxc1BQ/lib/python3.5/site-packages/django/template/defaulttags.py in render, line 165
Python Executable: /home/codism-7/.local/share/virtualenvs/django-njoxc1BQ/bin/python3
Python Version: 3.5.2
答案 0 :(得分:0)
用户request.user
代替User.objects.get(id=pk)
,而用户request.user.userprofile
代替UserProfile.objects.get(user_id=pk))
答案 1 :(得分:0)
找到了ans。它不使用对象名称,而是应该放置与对象不同的名称。例子
object12
context ={
'object12': instance1, # Change here
'u_form': u_form,
'p_form': p_form
}
,在模板中,我们可以将其作为{{ object12.first_name }}