Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django, updating a user profile with a ModelForm

Tags:

python

django

I'm trying to display a simple ModelForm for a user's profile and allow the user to update it. The problem here is that my logic is somehow flawed, and after a successful form.save() call, the old values show on the page. It isn't until a refresh that the appropriate value is shown. 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'm just looking to update an existing profile, not add a new one.

like image 689
randombits Avatar asked Dec 01 '09 02:12

randombits


2 Answers

Try this:

@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))
like image 132
Wogan Avatar answered Sep 21 '22 12:09

Wogan


You could also use a generic 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')
like image 34
Benjamin Wohlwend Avatar answered Sep 18 '22 12:09

Benjamin Wohlwend