Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delete instance in django ModelForm

I am trying to delete an instance form in django ModelForm but it’s not deleting,
the update part is working perfectly though.

my views.py:

def update_component(request, pk):
    component = Component.objects.all()
    component_id = Component.objects.get(id=pk)
    form = ComponentModelForm(instance=component_id)
    if request.method=='POST' and 'form-update' in request.POST:
        form = ComponentModelForm(request.POST,request.FILES, instance=component_id)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(request.path_info)
    if request.method=='POST' and 'form-delete' in request.POST:
        form.delete()
        return redirect('/maintenance')
    context = {
        'components': component,
        'form': form,
        'component_id':component_id,
    }        
    return render(request, 'update_component.html', context)

the delete form:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    <form class="component-delete-button"><input name="form-delete" type="submit"
    class="button1" value='Delete Component' /></form>

>Solution :

You don’t need a form to delete an item: a form is a way to handle HTML form input and transforms it into data that is more accessible to Python.

In case of a delete, you delete the instance, so:

def update_component(request, pk):
    component = Component.objects.all()
    component_id = Component.objects.get(id=pk)
    form = ComponentModelForm(instance=component_id)
    if request.method=='POST' and 'form-update' in request.POST:
        form = ComponentModelForm(request.POST,request.FILES, instance=component_id)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(request.path_info)
    if request.method=='POST' and 'form-delete' in request.POST:
        component_id.delete()
        return redirect('/maintenance')
    context = {
        'components': component,
        'form': form,
        'component_id':component_id,
    }        
    return render(request, 'update_component.html', context)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading