[英]django print loop value only once
我有一個視圖,我得到限制的約會列表..
def HospitalAppointmentView(request, pk, username, hdpk):
todays_appointments = DoctorAppointment.objects.filter(hospital__id=pk, doctor__id=hdpk, appointment_date=today).order_by("-appointment_date")[:5]
return render_to_response('doctor_appointment_list.html', {"todays_appointments": todays_appointments}, context_instance=RequestContext(request))
在我的模板中:
{% for appointment in todays_appointments %}
<h3>{{appointment.doctor.username}}<h3>
<tr>
<td>{{appointment.appointment_date}}</td>
<td>{{appointment.first_name}} {{appointment.middle_name}} {{appointment.last_name}}</td>
<td>{{appointment.user}}</td></tr>
<a href="{% url "all_appointments" appointment.hospital.id appointment.doctor.id%}">
See All</a>
{% endfor %}
它重復顯示5次,除了“查看全部”之外,正確顯示了5個約會,我想將醫生的用戶名作為標題,並且還要打印5次。
當我點擊“查看全部”時,我想重定向到可以看到所有約會的頁面。 喜歡:
def HospitalAppointmentView(request, pk, username, hdpk):
todays_appointments = DoctorAppointment.objects.filter(hospital__id=pk, doctor__id=hdpk, appointment_date=today).order_by("-appointment_date")
return render_to_response('all_appointment.html', {"todays_appointments": todays_appointments}, context_instance=RequestContext(request))
如果我在for循環外編寫“查看全部”,則無法訪問hospital.id和doctor.id,在循環內無法訪問“查看全部” 5次,並且{{appointment.doctor.username}}也是如此。
如何在不打印的情況下重定向5次,並且網址中需要所有信息並且{{appointment.doctor.username}}被打印一次?
你可以使用{{forloop.first}}
來實現第一次迭代。 喜歡 ...
{% for appointment in todays_appointments %}
{% if forloop.first %}
<h3>{{appointment.doctor.username}}<h3>
{%endif%}
...
{%endfor%}
{{todays_appointments.0.doctor.username}}
和你的正常循環。
{% for appointment in todays_appointments %}
....
{% endfor %}
但羅恩的回答更明智
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.