joselegit
joselegit

Reputation: 533

Django delete formset

I have a template where the user search for some records to delete.

I am having troubles trying to figure out how to delete multiple records from a model.

    def XMLFieldsView(request):
        if request.method == 'POST':
           lista = request.POST.getlist('eliminar')
           """ Here I am lost """
        else:
           lista = 'nada'
           form = BuscarServicioForm()
           idxml = request.GET.get('id_xml')
           tabla = XMLFORMTable(XML_FORM.objects.filter(id_xml = 00))
           try:
              idxml = idxml
           except ValueError:
              idxml = 00
           if idxml:
              tabla = XMLFORMTable(XML_FORM.objects.filter(id_xml = idxml))
           RequestConfig(request,paginate={"per_page":60}).configure(tabla)


        return render_to_response('listacampos.html',
                                  {'table':tabla,'form':form,'lista':lista},
                                  context_instance=RequestContext(request))

The user using the form

BuscarServicioForm pick a group of records, where he can choose which records to delete.

But I don't if I need to do this with a formset or I can take the value from the table turning the HTML table into a form

<form method="POST" id="table_form">
<table >
....
</table>
<input type="submit">
</form>

and get the post data to delete the records.

I am using django-tables2 to render the table in this way:

TEMPLATE_CHECK = """
<span class="input-group-addon">
        <input type="checkbox" id="id_eliminar" name="eliminar">
</span>
"""
class XMLFORMTable(tables.Table):
      eliminar = tables.TemplateColumn(TEMPLATE_CHECK,verbose_name='Eliminar')
      class Meta:
            model = XML_FORM
            exclude = ['id_form','obs']

I was thinking to use a formset but I don't how to do that.

Any advice or guide please

Thanks in advance

Upvotes: 0

Views: 663

Answers (1)

Zartch
Zartch

Reputation: 1025

The html template has to know the pk of the object to get the list of the objects.

class XMLFORMTable(tables.Table):
      eliminar = tables.CheckBoxColumn(accessor='pk')
      class Meta:
            model = XML_FORM
            exclude = ['id_form','obs']

If you give the pk to the value of the checkbox, you retrieve the value list of checked elements.

import render

def XMLFieldsView(request):
    if request.method == 'POST':
       lista = request.POST.getlist('eliminar')
       """ Here I am lost """
       for pk in lista:
           get_object_or_404(ElObjeto, pk=pk).delete()
    else:
       ....

    return render(request, listacampos.html,{'table':tabla,'form':form,'lista':lista})

Also render, is a shortcut for render_to_response in that will automatically use RequestContext

Upvotes: 1

Related Questions