我在视图之间使用两个会话。这些会话及其相应的['key']的值将为空列表或包含值的列表。
您可以在代码中看到,请求会话密钥始终存在,因为它已使用列表设置为空或不为空。问题是,即使列表具有值,它的行为也好像是空的。它总是与第二个视图的模板中的else块一起出现。
视图1:初始化列表并设置会话
def apply_fees(request):
included = []
excluded = []
if request.POST:
form = applyfees_form(request.POST)
if request.POST.get('applyBtn'):
checks_list = request.POST.getlist('checks')
payment_id = request.POST.get('fee_selection')
for item in checks_list:
stud = User.objects.get(username=item)
fee = Fee.objects.get(payment_id=payment_id)
obj, created = FinedStudent.objects.get_or_create(pays_id=fee, stud_id=stud)
if created:
name = stud.first_name + ' ' + stud.last_name
excluded.append(name)
else:
obj.save()
name = stud.first_name + ' ' + stud.last_name
included.append(name)
request.session['included'] = included
request.session['excluded'] = excluded
return render(request, 'studentapp/confirmApplyFees.html')
我可以说request ['included']有一个包含值的列表,因为obj.save被触发了,所以我假设append方法也被触发了。
视图2:在上下文中设置具有请求会话数据的字典键值
def confirm_apply(request):
context = {
'included': request.session.get('included'),
'excluded': request.session.get('excluded'),
}
return render(request, 'studentapp/confirmApplyFees.html', context)
视图2的模板:
<table class="table">
<thead class=" text-primary">
<th>Name</th>
</thead>
<tbody>
{% if included %}
{% for item in included%}
<tr>
<td>{{item}}</td>
</tr>
{%endfor%}
{% else %}
<tr>
<td>No students to be shown</td>
</tr>
{% endif %}
</tbody>