Updating several records at once using Django

情到浓时终转凉″ 提交于 2019-12-20 11:21:21

问题


I want to create a list of records with checkboxes on the left side....kinda like the inbox in Gmail. Then if a user selects some or all of these checkboxes, then the selected record(s) can be updated (only one field will be updated BTW), possibly by clicking a button.

I'm stuck on how to do this though....ideas?

Display Code

{% for issue in issues %}
   <tr class="{% cycle 'row1' 'row2' %}">
      <td><input name="" type="checkbox" value="{{ issue.id }}" /></td>
      <td>{{ issue.description }}</td>
      <td>{{ issue.type }}</td>
      <td>{{ issue.status }}</td>
      <td>{{ issue.date_time_added|date:"d, M Y" }}</td>
      <td>{{ issue.added_by }}</td>
      <td>{{ issue.assigned_to }}</td>
   </tr>
{% endfor %}

回答1:


Use the queryset update() method:

id_list = list_of_ids_from_checkboxes
MyModel.objects.filter(id__in=id_list).update(myattribute=True)

Your display HTML is missing a name value for the checkboxes. If you just have a single name across all checkboxes, then the list of IDs will be passed into a single POST variable, which you can get straight from request.POST (assuming you're submitting your form as a post, which you should be):

id_list = request.POST.getlist('checkboxname')


来源:https://stackoverflow.com/questions/2743802/updating-several-records-at-once-using-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!