enter image description here i want to allow users to update their profile informations but my problem is that when i submit the form it shows me this error and i can't see where the error is !!
@login_required
def update_profile(request):
if request.method == 'POST':
user_u = UpdateUser(request.POST)
profile_u = UpdateProfile(request.POST)
if user_u.is_valid() and profile_u.is_valid():
request.user.username = user_u.cleaned_data['username']
request.user.first_name = user_u.cleaned_data['first_name']
request.user.last_name = user_u.cleaned_data['last_name']
request.user.email = user_u.cleaned_data['email']
request.user.save()
prf = Profile.objects.get(user=request.user)
prf.Zip_code = profile_u.cleaned_data['Zip_code']
prf.Phone = profile_u.cleaned_data['Phone']
prf.save()
return redirect(reverse('profile'))
else:
data1 = {'username': request.user.username, 'email': request.user.email,
'first_name': request.user.first_name, 'last_name': request.user.last_name}
profile = Profile.objects.get(user=request.user)
data2 = {'Phone': profile.Phone, 'Zip_code': profile.Zip_code}
form1 = UpdateUser(initial=data1)
form2 = UpdateProfile(initial=data2)
return render(request, 'store/updateprofile.html', {'form1': form1, 'form2': form2})
I think it might probably help if you use consistent variable names over the entire scope of the method. Here in the POST
case you use user_u
and profile_u
, whereas in the GET
case (the last else
), you will use form1
and form2
.
As a result a POST request where (at least) one of the forms is invalid, will result in a render(..)
call, but without setting form1
and form2
.
In your view you also do a lot of things that are typically handled by a ModelForm
[Django-doc] , so I propose that you call the profile_u.save()
(and if not yet done, transform these forms into ModelForm
).
Finally you can use instance=...
to load the form with "initial values".
If we take these changes into account, we obtain the following view:
@login_required
def update_profile(request):
prf = Profile.objects.get(user=request.user)
if request.method == 'POST':
user_u = UpdateUser(request.POST, instance=)
profile_u = UpdateProfile(request.POST, instance=)
if user_u.is_valid() and profile_u.is_valid():
return redirect(reverse('profile'))
else:
user_u = UpdateUser()
profile_u = UpdateProfile()
return render(request, 'store/updateprofile.html', {'form1': user_u, 'form2': profile_u})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.