Editing the Form in Django creates new instance

后端 未结 2 1976
既然无缘
既然无缘 2021-02-14 02:31

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


        
相关标签:
2条回答
  • 2021-02-14 03:12

    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,
        })
    
    0 讨论(0)
  • 2021-02-14 03:17

    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()
    
    0 讨论(0)
提交回复
热议问题