How to use for loop and if condition in a Html Template - Django



Here we are going to display a Student's Timetable using for loop and if condition in a Html Template in Django.




As shown above a single bracket and a percentage symbol is to be used for the declaration of both For-Loop and if condition in Django Html Template. Variable used in a For-Loop must always have to be an iterable one or it may end in non-iterable error. For example models.assign_time_table.objects.all().filter() or it has to be something like list. You can't iterate through a single object. As for If condition the variable has to be a non-iterable variable else it can't be used in If condition.


mon_time_10 time which means Monday@10 a single object which also can be looped because if it is filtered with objects.all().filter(). Suppose if the variable is filtered with objects.get() which will cause a non-iterable error.


Make sure you filter as much as you can in the views page not in the Html Template. Use Template For and If tags if required.

Code




0 Comments