如何在Django模板中使用“ if”增加变量?

时间:2018-11-11 01:35:40

标签: django django-models django-forms

我正在尝试在Django模板中使用“ if”增加变量,我已经尝试了该站点上的所有建议,但没有一个解决了我的问题。 有views.py

class IndexView(generic.ListView):
template_name = 'home/index.html'
context_object_name = 'problemes'

def get_context_data(self, **kwargs):
    context_data = super().get_context_data(**kwargs)
    context_data['problemes'] = Probleme.objects.all()
    context_data['commentaires'] = Commentaire.objects.all()
    return context_data


def get_queryset(self):
    result_list = self.get_context_data
    return result_list

和index.html

....
 {% for problem in problemes %}
                                        {% with number_comment= 0%}
                                        {% for comment in commentaires %}
                                        {% if comment.probleme.id == problem.id %}
                                        {% number_comment ++ %}
                                        {% endif %}
                                        {% endfor %}

                                    <tr data-status="pagado">
                                    <td>
                                        <div class="votes">
                                            <div class="mini-counts"><span title="74 votes">74</span></div>
                                            <div>votes</div>
                                        </div>


                                    </td>
                                    <td>
                                        <div class="status answered-accepted" title="one of the answers was accepted as the correct answer">
                                            <div class="mini-counts"><span title="2 answers">{{ number_comment }}</span></div>
                                            <div>answers</div>
                                        </div>
                                        {% endwith %}
                                        ....

1 个答案:

答案 0 :(得分:0)

如果像在index.html中一样直接引用number_comment,则可以使用add模板标记对其进行递增。当然,这只会在模板中递增数字,而不会保存到数据库中。

{{ number_comment|add:"1" }}