How to save updates to object via the Django form?

Asked

Viewed 103 times

0

I have an application and when I send the data in the form to be updated it works ( the data are shown in the form) but when I click save the update it repeats the initial data and saves nothing.

Follows code :

view py.

def Atualizar(request, id):
    atualizar = get_object_or_404(Local, id=id)
    local = FormularioLocal(instance=atualizar)
    if local.is_valid():
        local_banco = local.save(commit=False)
        local_banco.save()
        return redirect("gerenciar_local")

    form = {}
    form['local'] = local

    return render(request, "local/atualizar.html", form)

And the template to render the form with the data passed :

<h1> Atualizar <h1>

<form method="post">
  {% csrf_token %}
  {{ local.as_p }}
  <button type="submit">Salvar</button>
</form>

How do I save upgrades ?

1 answer

0


You are using a Modelform?

# forms.py
# ...
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

# views.py
# ...    
def atualizar(request, id): 
    instance = get_object_or_404(MyModel, id=id)
    form = MyForm(request.POST or None, instance=instance)
    if form.is_valid():
        form.save()
        return redirect('next_view')
    return render(request, 'my_template.html', {'form': form}) 

Behold: https://stackoverflow.com/questions/4673985/how-to-update-an-object-from-edit-form-in-django

Or better yet, use the Updateview.

  • Yes, I’m using Modelform. This answer you gave worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.