Django updating user profile using ModelForm

I am trying to display a simple ModelForm for a user profile and allow the user to update it. The problem here is that my logic is somehow messed up, and after a successful call to form.save (), the old values ​​are displayed on the page. Until it is shown that the corresponding value is displayed. What is wrong here?

@login_required def user_profile(request): success = False user = User.objects.get(pk=request.user.id) upform = UserProfileForm(instance=user.get_profile()) if request.method == 'POST': userprofile = UserProfileForm(request.POST, instance=user.get_profile()) if userprofile.is_valid(): up = userprofile.save(commit=False) up.user = request.user up.save() success = True return render_to_response('profile/index.html', locals(), context_instance=RequestContext(request)) 

I just want to update an existing profile, not add a new one.

+7
python django
source share
2 answers

Try the following:

 @login_required def user_profile(request): success = False user = User.objects.get(pk=request.user.id) if request.method == 'POST': upform = UserProfileForm(request.POST, instance=user.get_profile()) if upform.is_valid(): up = upform.save(commit=False) up.user = request.user up.save() success = True else: upform = UserProfileForm(instance=user.get_profile()) return render_to_response('profile/index.html', locals(), context_instance=RequestContext(request)) 
+8
source share

You can also use the general view :

 from django.views.generic.create_update import update_object @login_required def user_profile(request): return update_object(request, form_class=UserProfileForm, object_id=request.user.get_profile().id, template_name='profile/index.html') 
+3
source share

All Articles