Editing a form in Django creates a new instance

I edit the form, it loads the data correctly, buying, when I click save, it creates a new record in the database.

Here are the presentation functions

def create_account(request): if request.method == 'POST': # If the form has been submitted... form = AccountForm(request.POST, request.FILES) # 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() # An unbound form return render_to_response('account_form.html', { 'form': form, }) 

-

 def edit_account(request, acc_id): f = Account.objects.get(pk=acc_id) if request.method == 'POST': # If the form has been submitted... form = AccountForm(request.POST, request.FILES) # 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, }) 

I really need to have a separate editing function and split by delete. Can i do everything in one function

template

  <form action="/account/" method="post" enctype="multipart/form-data" > {% csrf_token %} {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input type="submit" value="Send message" /></p> </form> 
+7
source share
2 answers

Missing instance argument in 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 this to the add / edit form, you can add / edit at the same time.

It will add if instance=None and update if instance is the 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, }) 
+11
source

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() 
+1
source

All Articles