Django获取所有复选框值,选中或取消选中

时间:2017-11-12 04:57:49

标签: django forms checkbox

使用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 %}

显示每个帐户的状态,用户可以更新它们。

更新:包括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(...)

问题:

  1. 如何检索所有复选框,选中还是取消选中?

  2. 检索到的列表如何包含每个帐户的状态,以便我可以相应地设置帐户的is_active字段?

1 个答案:

答案 0 :(得分:1)

1。要取消选中,您可以使用cmd.run

{% if salt['cmd.run']('hostname -f') == 'domain1' %}

更多指定;

.exclude

2。将帐户设置为User.objects.exclude(id__in=accounts)

account_ids = [u.id for u in User.objects.exclude(id__in=accounts)]

我认为你需要做的是: 如果帐户已选中,则设置为is_active,其他人User.objects.filter(id__in=accounts).update(is_active=True) User.objects.exclude(id__in=accounts).update(is_active=False) ,这是您的观点吗?

所以,这是我的建议;

is_active=True