[Answered ]-Edit a Model with an input. ValueError

2đź‘Ť

âś…

Like the above commenter said, the form isn’t posting any field named “id”. What you want is “edit_amount{{ id }}”.

Here’s an example of how to extract the ID from the form field name. It’s lacking exception catching and some other “gotchas” you’ll want to lookout for. But this is the basic idea.

I do suggest that you add a hidden form field with the ID instead of doing it this way though. You should also check the permissions of the user, and make sure that they’re able to modify that specific record.

@login_required
def edit(request):
   # Skipping the first couple lines.
   id = None
   for key in request.POST.keys():
       if 'edit_amount' in key:
           id = int(key[11:])

   position = InvestorPosition.objects.get(id=id)

   position.amount = Decimal(request.POST.get('edit_amount%s' % id))
   position.save()

   return HttpResponseRedirect(request.POST.get('next', '/portfolio/'))
👤damon

Leave a comment