1

I'm trying to run a simple update form that should update all object values in DB submitted from the form.

This is my update view that does nothing other than redirecting to the "/". No errors but no update either.

def update(request, business_id):
    if request.method == 'POST':
        form = BusinessForm(request.POST)

        if form.is_valid():
            t = Business.objects.get(id=business_id)
            t.save()
        return HttpResponseRedirect("/")
    else:
          ...

1 Answer 1

2

You are not updating any fields, use form.cleaned_data to get the form field values:

Once is_valid() returns True, the successfully validated form data will be in the form.cleaned_data dictionary. This data will have been converted nicely into Python types for you.

if form.is_valid():
    t = Business.objects.get(id=business_id)
    t.my_field = form.cleaned_data['my_field']
    t.save()

Also, consider using an UpdateView class-based generic view instead of a function-based:

A view that displays a form for editing an existing object, redisplaying the form with validation errors (if there are any) and saving changes to the object. This uses a form automatically generated from the object’s model class (unless a form class is manually specified).

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Thats what I thought, I just wasnt sure if Django is smart enough to grab all the values from the form as it is done with saving new data or if I have to define each field.
@WayBehind django is smart enough if you would use an UpdateView - I've also updated the answer. Hope that helps.
Thanks for the update. I wasnt aware of the UpdateView and will look into that!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.