问题
Using Django's User
model, I have the following template:
UPDATE: more detailed template
<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 %}
which shows the status of each account and the user may update them.
UPDATE: including GET and POST handling. As there are thousands of accounts, they are displayed using Django's pagination
.
In the 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(...)
Questions:
How do I retrieve ALL checkboxes, checked or un-checked?
How can the retrieved list contains the status of each account, so that I can set the account's
is_active
field accordingly?
回答1:
1. To get un-checked, you can using .exclude
User.objects.exclude(id__in=accounts)
more specify;
account_ids = [u.id for u in User.objects.exclude(id__in=accounts)]
2. set the account's as is_active
or not.
User.objects.filter(id__in=accounts).update(is_active=True)
User.objects.exclude(id__in=accounts).update(is_active=False)
I think what exacly you need to do is:
If accounts is checked then set to is_active=True
and the others is_active=False
, that's your point right?
So, this a suggestion from me;
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)
来源:https://stackoverflow.com/questions/47245598/django-gets-all-checkboxes-values-checked-or-un-checked