[Fixed]-Django – best way of storing data created on the fly for a view/template

1πŸ‘

βœ…

You can store your data in a list of dictionaries:

data = [
    {
        "template_name": "RTR-01",
        "device_name": "EDGE"
    },
    {
        "template_name": "SW-01",
        "device_name": "CORE"
    },
]

Then you will need to update the template’s context by overriding the render_to_response method.

def render_to_response(self, context, **kwargs):
    context.update({"data": data})
    return super().render_to_response(context, **kwargs)

And then you can iterate in your template

<ul>
{% for item in data %}
<li>{{item.template_name}}</li>
<li>{{item.device_name}}</li>
{% endfor %}

0πŸ‘

A list of dicts seems best suited:

context = [
    {
        'template_name': 'RTR-01',
        'device': 'EDGE',
    },
    {
        'template_name': 'RTR-02',
        'device': 'EDGE',
    },
    {
        'template_name': 'SW-01',
        'device': 'CORE',
    },
]

You use classes when you want to associate behaviour to your data, which does not seem to be the case here.

Leave a comment