【发布时间】:2018-04-25 00:42:38
【问题描述】:
使用 Django 的 User 模型,我有以下模板:
更新:更详细的模板
<form method=POST action="...">
<table>
...
{% for account in accounts %}
<tr>
<td>
{{ account.username }}
</td>
<td>
<input type=checkbox name=account value="{{ account.id }}" {% if account.is_active %}checked{% endif %}>
</td>
</tr>
{% endfor %}
</table>
<input type=submit value=Submit>
</form>
{% for pg in paginator.page_range %}
{% if queryset.number == pg %}
<li><span>{{ pg }}</span></li>
{% else %}
<li><a href=".../?page={{ pg }}">{{ pg }}</a></li>
{% endif %}
{% endfor %}
显示每个帐户的状态,用户可以更新它们。
UPDATE:包括 GET 和 POST 处理。由于有数千个帐户,它们使用 Django 的pagination 显示。
在views:
def account(request):
if request.method == 'GET':
users = User.objects.all()
paginator = Paginator(users, 30)
page = request.GET.get('page')
accounts = paginator.page(page)
...
return render(request, 'account/account.html', {'accounts':accounts, 'paginator':paginator}
# POST
accounts = request.POST.getlist('account') # This will get only the `checked` ones
for account in User.objects.filter(id__in=accounts):
if account is checked: # Only hypothetical ...
account.is_active = True
else:
account.is_active = False
account.save()
return redirect(...)
问题:
如何检索 ALL 复选框(选中或未选中)?
如何在检索到的列表中包含每个账户的状态,以便我可以相应地设置账户的
is_active字段?
【问题讨论】:
-
请使用该功能更新您的完整视图。我需要知道您的
accounts..的上下文。 -
问题已更新。