WayBehind
WayBehind

Reputation: 1697

Django Update Object in Database

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:
          ...

Upvotes: 1

Views: 203

Answers (1)

alecxe
alecxe

Reputation: 473863

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).

Upvotes: 2

Related Questions