Skip to content Skip to sidebar Skip to footer

Editing The Form In Django Creates New Instance

I am editing the form , it loads data correctly buy when i hit save it creates new entry in database. Here is the view functions def create_account(request): if request.meth

Solution 1:

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.

defedit_account(request, acc_id=None):
    if acc_id:
        f = Account.objects.get(pk=acc_id)
    else:
        f = Noneif request.method == 'POST': # If the form has been submitted...
        form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST dataif form.is_valid(): # All validation rules pass
            form.save()
            return HttpResponseRedirect('/thanks/') # Redirect after POSTelse:
        form = AccountForm(instance=f) # An unbound formreturn render_to_response('account_form.html', {
        'form': form,
    })

Solution 2:

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

Post a Comment for "Editing The Form In Django Creates New Instance"