i'm trying to add a feature for users to update thier profile, but i want to be able to get thier existing informations so they don't have to fill all the form again. I have tried request.POST
on the form but it doesn't work, it does not update the form with the existing user informations.
views.py
def profile_update(request):
info = Announcements.objects.all()
categories = Category.objects.all()
Profile.objects.get_or_create(user=request.user)
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'Acount Updated Successfully!')
return redirect('userauths:profile')
else:
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form,
'info': info,
'categories': categories
}
return render(request, 'userauths/profile_update.html', context)
# profile update function
def profile_update(request):
info = Announcements.objects.all()
categories = Category.objects.all()
Profile.objects.get_or_create(user=request.user)
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'Acount Updated Successfully!')
return redirect('userauths:profile')
else:
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form,
'info': info,
'categories': categories
}
return render(request, 'userauths/profile_update.html', context)
You can access the model instance associated with your form with {{form.instance}}
.
{{p_form.instance.first_name}}
EDIT:
Here while saving the ProfileUpdateForm you are not handling the field user so you can handle user in your profile form like this.
if u_form.is_valid() and p_form.is_valid():
user = u_form.save()
profile = p_form.save(commit=False)
profile.user = user
profile.save()