1👍
✅
You can pass instance
parameter while instantiating the form. In that case you don’t have to create dict to populate form, or iterate over field to save them.
Your view can be changed as
def profile_edit(request,
template_name,
user_id,
edit_form=ProfileForm,):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts:login'),
)
#ensure the request user is the edit user
if request.user.pk!=int(user_id):
raise Http404
if request.method == 'POST':
form = edit_form(data=request.POST, instance=request.user.profile)
if form.is_valid():
#no need for edit method
updated_profile = form.save()
return HttpResponseRedirect(reverse('accounts:profile',kwargs={'user_id':user_id}))
else:
#no need to crate dict
form = edit_form(instance=request.user.profile)
context = {
'form': form,
}
return TemplateResponse(request, template_name, context,)
Source:stackexchange.com