AlliDeacon
AlliDeacon

Reputation: 1495

Updating Record with ModelForm

I am working on calling up a pre-populated form based on user input. I want to allow editing of the record in the resulting form, and then save the updates to the DB Record. Below is creating new records, not updating existing and I'm stuck on next steps.

   def mod_customer(request):
        params = json.loads(request.body)
        selection = params['cst_id']
        obj = AppCustomerCst.objects.get(id_cst=selection)
        instance = get_object_or_404(AppCustomerCst, id_cst=selection)
        form = CustomerMaintForm(request.POST or None, instance=instance)
        if '_edit' in request.POST:
            if form.is_valid():
                form.save()
                return redirect('customers')
    
        elif form.is_valid() and '_delete' in request.POST:
            # just for testing purposes. once mod is working, will update with delete
            # AppCustomerCst.objects.filter(id_cst=selection).delete()
            context = {'form': form}
            return render(request, 'mod_customer.html', context=context)
    
    
        else:
            context = {'form': form}
            return render(request, 'mod_customer.html', context=context)

Upvotes: 1

Views: 49

Answers (1)

Okkie
Okkie

Reputation: 335

This is after @BlackDoor step.

Your code might not reach form.save(). That is why the records are not being updated.

To know for sure do something like print(form.is_valid()) if this is False then do form.errors to see where it goes wrong.

Upvotes: 1

Related Questions