Skip to main content
 首页 » 编程设计

python之django 从模板中的列表访问值

2025年04月02日41yjmyzz

我的网页在查看时目前是空白的,查看其他示例似乎我正在正确访问这些值,但我没有获得任何数据。 我通过打印列表检查了我的列表,它们都有大量数据

模板

{% extends 'oncall/base.html' %} 
 
{% block content %} 
    {% for pol in lstPolicy %} 
        <h2>1 - {{ pol.Name }}</h2> 
        {% for user in lstUsers %}   
            {% if user.Policy == pol.Name %} 
                <h3>2 -{{ user.Level }}</h3> 
                <p>  
                    Mobile: {{ user.Mobile }} 
                    From: {{ user.StartTime }} on {{ user.StartDate }} 
                    Until: {{ user.EndTime }} on {{ user.EndDate }} 
                </p> 
            {% endif %}  
        {% endfor %} 
    {% endfor %} 
{% endblock %} 

基础模板

{% load staticfiles %} 
<html> 
    <head> 
        <title>IT on call Rota</title> 
    </head> 
    <body> 
        <a href="/">Home</a> 
        {% block content %} 
        {% endblock %} 
    </body> 
</html> 

查看

# Create your views here. 
def index(request): 
    lstPolicy = [] 
    lstUsers = [] 
    for objPolicy in objPolicyData['escalation_policies']: 
        strPolicyName = objPolicy['name']    
        if strPolicyName.lower().find('test') == -1: 
            classPolicy = Policy() 
            classPolicy.Name = strPolicyName 
            lstPolicy.append(strPolicyName)  
            for objOnCall in objPolicy['on_call']: 
                classUser = User() 
                classUser.Policy = strPolicyName 
                strLevel = '' 
                if objOnCall['level'] == 1: 
                    strLevel == 'Primary on call' 
                elif objOnCall['level'] == 2: 
                    strLevel == 'Backup on call'  
                elif objOnCall['level'] == 3: 
                    strLevel == 'Tetiary on call' 
                classUser.Level = strLevel 
                classUser.StartDate = getDate(objOnCall['start']) 
                classUser.EndDate = getDate(objOnCall['end']) 
                classUser.StartTime = getTime(objOnCall['start']) 
                classUser.EndTime = getTime(objOnCall['end']) 
                objUser = objOnCall['user'] 
                classUser.Name = objUser['name'] 
                classUser.Mobile = getUserMobile(objUser['id']) 
                lstUsers.append(classUser)    
    return render(request, 'oncall/rota.html', {'lstUsers': lstUsers, 'lstPolicy': lstPolicy}) 

html 生成

<html> 
    <head> 
        <title>IT on call Rota</title> 
    </head> 
    <body> 
        <a href="/">Home</a> 
 
 
        <h2>1 - </h2> 
 
 
 
 
 
 
 
 
 
 
 
 
        <h2>1 - </h2> 
 
 
 
 
 
 
 
 
 
 
 
 
        <h2>1 - </h2> 
 
 
 
 
 
 
 
 
 
 
 
 
        <h2>1 - </h2> 
 
 
 
 
 
 
 
 
 
 
 
 
        <h2>1 - </h2> 
 
 
 
 
 
 
 
 
 
 
 
 
 
    </body> 
</html> 

请您参考如下方法:

您添加 strPolicyName :

lstPolicy.append(strPolicyName)  

但是你必须添加classPolicy:

lstPolicy.append(classPolicy)  

字符串没有名称属性:)