1

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:

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

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.