How to show level from Django MPTTModel in template?

42 Views Asked by At

I'm using django-mptt to store a hierarchical data (A Story with a number of scenes, in which each scene is a child of another scene) in DB. The data is for each node(scene) is collected from the user using a form. When the user is adding data to the form I like to show which level the current node is going to be saved.

This is my model

class Scene(MPTTModel, models.Model):
    story_id = models.ForeignKey(Story, on_delete=models.CASCADE, default=None)
    created_at = models.DateTimeField(auto_now_add=True)
    description = models.TextField(max_length=1000)
    choice1 = models.TextField(max_length=1000, default=None)
    choice2 = models.TextField(max_length=1000, default=None)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['id']

My forms.py


class SceneForm(forms.ModelForm):
    class Meta:
        model = Scenario
        fields = ['description','choice1', 'choice2']
        readonly_fields = ['level']

My scene.html

{% extends "base.html" %}

{% block content %}
    <h2>Create scene for Level {{form.level}}</h2>
    <h1>{{ form.title }}</h1>
    <p>{{ form.desc }}</p>
    <form class="scenario-designer" action="{% url 'App:designscene' %}" method="post">
      {% csrf_token %}
      <table>
        {{form.as_table}}
      </table>
      <button type="submit" name="save" value="save">Save</button>
    </form>
{% endblock %}

The level is not showing, when I try form.level in debug console it shows AttributeError: 'SceneForm' object has no attribute 'level'. I was under the impression that since MPTTModel have level field it could be accessed using form.. Any pointers on how to access the level attribute in the template is greatly appriciated. I'm very new to django so please forgive my lack of understanding.

0

There are 0 best solutions below