如果条件在django模板中的Inner Loop中不起作用

时间:2018-02-01 22:09:43

标签: python django django-models django-templates django-views

我不知道是什么问题而且我已经被困在这里好几个小时了。可能有重复的问题,但没有一个可以让我脱离这个。

我在内部循环中使用if条件来检查inner的属性是否等于外部循环但是如果条件永远不为真,即使数据是相同的。

我已单独打印数据,这两个属性打印数据均值数据是否正确。但是,当我使用if条件时,它会转到其他地方

数据

以下是我正在使用的数据:

activityy.activity_name = [Table Tennis,Swimming Pool, Football ] 
slot.activity = [Table Tennis,Table Tennis,Table Tennis,Table Tennis,Swimming Pool, Football]

activities.html

{% for activityy in all_activities%}
    <div style="margin-left: 450px; padding: 15px; border-radius: 5px; background-color: #dfdfdf;height: 150px; width: 800px; margin-top: 20px; text-align: center">
    {% for slot in all_slots  %}
        {% if slot.activity == activityy.activity_name %}
            <div style="background-color: #3a589a; padding: 15px; width: 120px; height: 120px; float: left; border-radius: 5px;">
                <span style="color: #f1f1f1; font-size: 20px;"> {{ activityy.activity_name}}</span><br>
            </div>
        {% else %}
            <div style="background-color: #589a; padding: 15px; width: 120px; height: 120px; float: left; border-radius: 5px;">
                <span style="color: #f1f1f1; font-size: 20px;"> {{ slot.activity}}</span><br>
            </div>
        {% endif %}
    {% endfor %}
    </div>
{% endfor %}

Views.py

def activities(request):
    if request.user.is_authenticated:
        template = loader.get_template('sklc/activities.html')
        slots = []
        now = datetime.datetime.now()
        datee = now.strftime("%Y-%m-%d")
        if request.method == 'POST':
            dat = request.POST['date']
            if dat:
                datee = dat

        print("dateesss: " , datee)
        activitiess = Activities.objects.all();
        for activityy in activitiess:
            slot = ActivitySlots.objects.filter(dates=datee).filter(activity__activity_name=activityy.activity_name)
            for slott in slot:
                slots.append(slott)

        context = {
            'all_activities': activitiess,
            'all_slots': slots
        }
        return HttpResponse(template.render(context, request))
    else:
        messages.error(request, "Please Login First")
        return redirect("/login")

models.py

class Activities(models.Model):
    activity_name = models.CharField(max_length=50)

    def __str__(self):
        return self.activity_name

class ActivitySlots(models.Model):
    dates = models.DateField()
    available = models.BooleanField()
    activity = models.ForeignKey(Activities)
    time = models.CharField(max_length=50)

    def __str__(self):
        return self.time

1 个答案:

答案 0 :(得分:1)

我使用

解决了这个问题
{% if slot.activity == activityy %}

Butt仍然不知道为什么它不能与 activityy.activity_name 一起使用,因为 activityy activityy_activity_name 正在打印相同的东西。< / p>