I need to create a pretty straight forward form with Django but seems to be unable to find the proper tool for it, maybe because of the lack of vocabulary on what I want :
I have a table of n rows (n varies), each row represents a database object. I want to put a checkbox in front left of each row to be able to select multiple rows and apply an action placed in a multiplechoice widget at the top.
I thought about "serialize" a deleteview with formset but anyway I don't know how to add extra actions (apart from delete).
Any valuable information on direction to take would be welcome, thanks.
答案 0 :(得分:1)
您可以尝试使用Django Tables 2。尝试这样:
import django-tables2 as table
class YourTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk') # Override here to show checkbox
class Meta:
model = YourModel
template_name = 'django_tables2/bootstrap.html'
def some_view(request):
if request.method == "GET":
table = YourTable(YourModel.objects.all())
return render(request, 'template.html', context={'table': table})
<form method="post">
{% csrf_token %}
<select name="action_options">
<option value="delete">Delete</option>
<option value="hard_delete">Hard Delete</option>
</select>
{% load render_table from django_tables2 %} // loading template tag
{% render_table table %} // catching context as table from view
<input type="submit" class="btn btn-primary" value="Delete">
</form>
def some_view(request):
...
if request.method == "POST":
pks = request.POST.getlist("selection") # handle selection from table
action = request.POST.get('action_options')
selected_objects = YourModel.objects.filter(pk__in=pks)
if action == 'delete':
selected_objects.delete()
# Rest of your Logic