Please help me. I am trying to update the profile in which username and email are updated but the image dose not. My code is….
profile.html
JavaScript
x
13
13
1
<form method="POST" enctype="multipart/form-data">
2
{% csrf_token %}
3
<fieldset class="form-group">
4
<legend class="border-bottom mb-4">Profile Info</legend>
5
{{ u_form|crispy }}
6
{{ p_form|crispy }}
7
</fieldset>
8
<br>
9
<div class="form-group">
10
<button class="btn btn-outline-info" type="submit">Update</button>
11
</div>
12
</form>
13
views.py
JavaScript
1
21
21
1
@login_required
2
def profile(request):
3
if request.method == 'POST':
4
u_form = UserUpdateForm(request.POST, instance=request.user)
5
p_form = ProfileUpdateForm(request.FILES, instance=request.user.profile)
6
if u_form.is_valid() and p_form.is_valid():
7
u_form.save()
8
p_form.save()
9
messages.success(request, f'Account Successfully Updated!')
10
return redirect('profile')
11
12
else:
13
u_form = UserUpdateForm(request.POST, instance=request.user)
14
p_form = ProfileUpdateForm(request.POST, instance=request.user.profile)
15
16
context = {
17
'u_form' : u_form,
18
'p_form' : p_form
19
}
20
return render(request, 'users/profile.html', context)
21
forms.py
JavaScript
1
5
1
class ProfileUpdateForm(forms.ModelForm):
2
class Meta:
3
model = Profile
4
fields = ['image']
5
Advertisement
Answer
I believe your issue lies in views.py.
Firstly, you are checking to see if the method for retrieving the view is POST. If it is not, you are initializing a form with the POST data that is not present. I have simplified that for you below.
Secondly, you are not passing the POST information to the second form, only the files portion. Have you tried changing the p_form to take both parameters like below?
JavaScript
1
21
21
1
@login_required
2
def profile(request):
3
if request.method == 'POST':
4
u_form = UserUpdateForm(request.POST, instance=request.user)
5
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
6
if u_form.is_valid() and p_form.is_valid():
7
u_form.save()
8
p_form.save()
9
messages.success(request, f'Account Successfully Updated!')
10
return redirect('profile')
11
12
else:
13
u_form = UserUpdateForm(instance=request.user)
14
p_form = ProfileUpdateForm(instance=request.user.profile)
15
16
context = {
17
'u_form' : u_form,
18
'p_form' : p_form
19
}
20
return render(request, 'users/profile.html', context)
21