[Solved]-Editing the Form in Django creates new instance

17๐Ÿ‘

โœ…

You are missing the instance argument at the POST section.

Instead of this:

form = AccountForm(request.POST, request.FILES) # A form bound to the POST data

You should use this:

form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data

Once you add that to the add/edit form you will be able to add/edit at the same time.

It will add if instance=None and update if instance is an actual account.

def edit_account(request, acc_id=None):
    if acc_id:
        f = Account.objects.get(pk=acc_id)
    else:
        f = None

    if request.method == 'POST': # If the form has been submitted...
        form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = AccountForm(instance=f) # An unbound form

    return render_to_response('account_form.html', {
        'form': form,
    })
๐Ÿ‘คWolph

1๐Ÿ‘

Have you tried something like this?

 # Create a form to edit an existing Object.
     a = Account.objects.get(pk=1)
     f = AccountForm(instance=a)
     f.save()

# Create a form to edit an existing Article, but use
# POST data to populate the form.
    a = Article.objects.get(pk=1)
    f = ArticleForm(request.POST, instance=a)
    f.save()
๐Ÿ‘คjuankysmith

Leave a comment