I have a text file like generated from 100 Cisco switches like this:
['device1', 'device2', 'device3', 'device4', ....., deviec100]
and I want to show this information using loop in template. So I have something like this in my HTML file to loop through each device:
{% for x in devie_list %}
{{ x }}
{% endfor %}
But it is just adding a space between each character, so the result is like this: [ ' d e v i c e 1 ' , ' d e v i c e 2 , .... ]
How can I tell Django, to loop through each item within the commas? or better say each list item.
CodePudding user response:
You should first convert the device_list
into a list data type, which you can do with any of the following methods, and then iterate on it as you wrote:
Method 1: Using python json module
import json
device_list = json.loads(device_list)
Method 2: Using eval() function
device_list = eval(device_list)
Method 3: Using string type methods
device_list = device_list.strip('[]').replace('"', '').replace(' ', '').split(',')
CodePudding user response:
Your devie_list
is not a list of strings, but a string that looks like a list of strings.
You can use ast.literal_eval(…)
[Python-doc] to evaluate this as a Python literal, and thus obtain a list of strings:
from ast import literal_eval
devie_list = literal_eval(devie_list)
and thus use the result of this in the template.
CodePudding user response:
return this in your view or under your model:
#Your list is a string you can turn into a list like this
device_list_as_list = device_list[1:-1].split(',')
Template:
{% for x in devie_list_as_list %}
{{ x }}
{% endfor %}