django:选择多行时创建表格形式 [英] django : create table form when selecting multiple rows
问题描述
我需要使用Django创建一个非常简单的表单,但似乎无法为其找到合适的工具,也许是因为我想要的词汇缺乏:
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 :
我有一个n行的表(n个变化),每一行代表一个数据库对象。我想在每行的左侧放置一个复选框,以便能够选择多行并在顶部的多选小部件中应用一个动作。
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.
使用序列集序列化一个deleteview,但是无论如何我都不知道如何添加额外的操作(除delete之外)。
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.
推荐答案
您可以尝试使用 Django表2 。像这样尝试:
You can try with Django Tables 2. Try like this:
import django_tables2 as tables
class YourTable(tables.Table):
selection = tables.CheckBoxColumn(accessor='pk') # Override here to show checkbox
class Meta:
model = YourModel
template_name = 'django_tables2/bootstrap.html'
使用表在视图中:
Use table in View:
def some_view(request):
if request.method == "GET":
table = YourTable(YourModel.objects.all())
return render(request, 'template.html', context={'table': table})
模板
Template
<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>
更新视图以处理过帐请求
Update View to Handle Post Request
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
这篇关于django:选择多行时创建表格形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!