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
<form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <br> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form>
views.py
@login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Account Successfully Updated!') return redirect('profile') else: u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, instance=request.user.profile) context = { 'u_form' : u_form, 'p_form' : p_form } return render(request, 'users/profile.html', context)
forms.py
class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image']
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?
@login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Account Successfully Updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form' : u_form, 'p_form' : p_form } return render(request, 'users/profile.html', context)