How to add extra data to a Django MPTT model for display in template?

喜夏-厌秋 提交于 2019-12-02 21:57:58

问题


This question is related to this one.

My Django Model:

from mptt.models import MPTTModel, TreeForeignKey
class myModel(MPTTModel):
    myIntA = models.IntegerField(default=0)   
    myParent = TreeForeignKey('self', null=True, blank=True, related_name='children')

My View:

myModelList = myModel.objects.all()
for i in range(len(myModelList)):
    myModelList[i].myIntB = i

return render(
    request, 
    'myApp/myTemplate.html', 
    Context(
        {
            "myModels": myModelList,
        }
    )
)

Is the above legal? You can see that I added a variable myIntB to each myModel object. However when I try to print myIntB in the template below, nothing shows up. How can I access myIntB from the template? It is not a field I have defined for this model, nor do I want it to be. I just want myModel to be augmented with this extra variable during rendering of this particular template. And I need to use {% recursetree %} in the template file to display the tree structure inherent in a collection of myModels.

My Template:

{% load mptt_tags %}
<ul>
    {% recursetree nodes %}
        <li>
            {{node.id}} {{node.myIntA} {{node.myIntB}}
            {% if not node.is_leaf_node %}
                <ul>
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>

来源:https://stackoverflow.com/questions/19763241/how-to-add-extra-data-to-a-django-mptt-model-for-display-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!