Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django print loop value only once

I have a view where I am getting the list of appointments with limit..

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))

In my template:

{% for appointment in todays_appointments %}
    <h3>{{appointment.doctor.username}}<h3>
    <tr>
    <td>{{appointment.appointment_date}}</td>
    <td>{{appointment.first_name}} &nbsp;{{appointment.middle_name}} &nbsp; {{appointment.last_name}}</td>
    <td>{{appointment.user}}</td></tr>
    <a href="{% url "all_appointments" appointment.hospital.id appointment.doctor.id%}">
    See All</a>

{% endfor %}

Its showing the 5 appointments correctly except "See All" is repeated 5 times and I want to make doctor's username as title and its also being printed 5 times.

When I click "See All" I want to redirect to the page where all appointments can be seen. Like:

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))

If I write "See All" outside the for loop I cant access the hospital.id and doctor.id and inside the loop I m getting "See All " 5 times and same goes with {{appointment.doctor.username}}.

How can I redirect without being printed 5 times with all information needed in the url and {{appointment.doctor.username}} being printed once?

like image 846
varad Avatar asked Dec 19 '22 09:12

varad


1 Answers

You can use {{forloop.first}} for, it will be true for 1st iteration. Like ...

{% for appointment in todays_appointments %}

    {% if forloop.first %}
        <h3>{{appointment.doctor.username}}<h3>
    {%endif%}

    ...
{%endfor%}
like image 102
Rohan Avatar answered Dec 22 '22 10:12

Rohan