user2514231
user2514231

Reputation: 37

Django form not saving

I am trying to update the fields for a custom user using the same form as the one used for creating the user account. The user account works fine and form.is_valid() returns true leading to the save and redirect however in the code below the redirect never happens and the fields updated on the form are not saved when using the submit button. I feel like I am missing something simple but just can't see it. Is there a reason the view below wouldn't save the data updated on the form?

Thanks

def update_user(request):
    user = Customer.objects.get(pk=request.user.id)
    form = CustomerForm(instance=user)
    if request.method == 'POST':
        form = CustomerForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('success.html')

    args = {}
    args.update(csrf(request))
    args['form'] = form
    return render_to_response('update.html', args)

Upvotes: 0

Views: 90

Answers (1)

Kamil Rykowski
Kamil Rykowski

Reputation: 1459

Have you tried to print form._errors when the form is invalid? It's a good way of debugging issues like this. Here you have fixed code:

def update_user(request):
    user = Customer.objects.get(pk=request.user.id)
    form = CustomerForm(instance=user)
    if request.method == 'POST':
        form = CustomerForm(request.POST, instance=user) # HERE
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('success.html')

    args = {}
    args.update(csrf(request))
    args['form'] = form
    return render_to_response('update.html', args)

Additionally you could replace this code:

form = CustomerForm(instance=user)
if request.method == 'POST':
    form = CustomerForm(request.POST, instance=user) # HERE
    if form.is_valid():
        form.save()
        return HttpResponseRedirect('success.html')

with this one (works the same):

form = CustomerForm(request.POST or None, instance=user)
if form.is_valid():
    form.save()
    return HttpResponseRedirect('success.html')

Upvotes: 1

Related Questions