【问题标题】:Django gets all checkboxes values, checked or un-checkedDjango获取所有复选框值,选中或未选中
【发布时间】: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(...)

问题:

  1. 如何检索 ALL 复选框(选中或未选中)?

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

【问题讨论】:

  • 请使用该功能更新您的完整视图。我需要知道您的accounts..的上下文。
  • 问题已更新。

标签: django forms checkbox


【解决方案1】:

1.要取消勾选,您可以使用.exclude

User.objects.exclude(id__in=accounts)

详细说明;

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

2.设置账号是否为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 和其他is_active=False,这就是你的意思吗?

所以,这是我的建议;

def account(request):
    users = User.objects.all()
    template_name = 'account/account.html'

    if request.method == 'POST':
        account_ids = request.POST.getlist('account')

        users.filter(id__in=account_ids).update(is_active=True)
        users.exclude(id__in=account_ids).update(is_active=False)

        return redirect(...)

    paginator = Paginator(users, 30)
    page = request.GET.get('page')
    accounts = paginator.page(page)
    ....

    context = {'accounts': accounts, 'paginator': paginator}
    return render(request, template_name, context)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    • 1970-01-01
    • 2017-04-03
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多