Django中存入数据库的Python列表如何在模板友好展示?
Hey there! Let's get that symptom list displaying nicely in your Django template—here's what's going wrong and how to fix it:
First, the main issues:
- You’re using
datalist.itemswhich is meant for dictionaries, not lists. Yourdatalistis a standard Python list, so you don’t need the.itemssuffix. - You’re outputting raw list elements without structuring them into readable HTML, which is why you’re seeing the raw list syntax.
Your Raw Data
Just to confirm, your data looks like this (a Python list of strings):
[u'RASH ERYTHEMATOUS', u'PAIN', u'FEELING HOT', u'PRURITUS', u'PAIN OF SKIN', u'SKIN IRRITATION', u'PARAESTHESIA', u'DERMATITIS CONTACT']
Solution 1: Display as a Bulleted List (Cleanest Option)
Update your template code to loop directly over datalist and wrap each item in list elements:
<ul> {% for symptom in datalist %} <li>{{ symptom }}</li> {% endfor %} </ul>
This will render a proper unordered list, with each symptom as a separate bullet point—super easy for users to scan.
Solution 2: Display Each Item on a New Line
If you prefer a simpler layout without bullets, use line breaks instead:
{% for symptom in datalist %} {{ symptom }}<br> {% endfor %}
Quick Check for Your View
Make sure you’re passing the list correctly to the template context in your view function. For example:
def symptom_view(request): # Fetch your API data here, then assign to datalist datalist = [u'RASH ERYTHEMATOUS', u'PAIN', u'FEELING HOT', u'PRURITUS', u'PAIN OF SKIN', u'SKIN IRRITATION', u'PARAESTHESIA', u'DERMATITIS CONTACT'] return render(request, 'your_template.html', {'datalist': datalist})
That’s it! With these changes, your symptoms will display in a friendly, readable format instead of the raw list syntax.
内容的提问来源于stack exchange,提问作者Sapna Sharma

