首页 > 解决方案 > 无法在 Django 模板中获取字典值

问题描述

我正在尝试访问返回字典的类方法的值。我的功能是这样的:

 class GetData:
def __init__(self, api_key, ip, interface):
    self.api_key = api_key
    self.asa_ip = ip
    self.interface = interface
    self.auth_headers = {'X-Auth-Token': api_key, 'Content-Type': 'application/json'}

def data(self):
    req = requests.get('https://{}:/{}/entries'.format(self.ip, self.interface),
                       headers=self.auth_headers, verify=False)
    json_response = json.loads(req.content)
    data = {}
    for items in json_response['items']:
    ...

    return data  #it return dictionary     

在我的 view.py 中,我的代码如下所示:

   def class_data(request):
       interface_name = request.session.get('interface')
       ip = request.session.get('ip')
       api_key = request.session.get('api_key')
       peer = str(request.POST.get('Peer'))
       class_data = DataForm(interface_name, api_key, ip)
       return render(request, 'user/data.html', {'peer' : str(peer), 'class_data': class_data })

在我的 data.html 中,我试图访问 GetData 类中的数据:

       <h5>Data</h5>
            <p> {{ class_data.data.peer.pfs_group }}</p>

我没有收到任何错误,我在浏览器中看到一个空白页面。我已经尝试过这样调用类:

    {{ class_data.data[peer]['pfs_group'] }}

但是当我这样做时,我得到一个错误:

     django.template.exceptions.TemplateSyntaxError: 
     Could not parse the remainder: '[peer]['pfs_group']' from 'vpn_data.data[peer]['pfs_group']' 

我做错了什么??

标签: pythonhtmldjangotemplatesjinja2

解决方案


问题在于它peer是一个变量,但是当您将它用作键时,Django 只会将其视为文字字符串。

您应该在视图中进行查找并将结果值传递给模板:

   peer = str(request.POST.get('Peer'))
   class_data = DataForm(interface_name, api_key, ip)
   peer_data = class_data[peer']
   return render(request, 'user/data.html', {'peer_data': peer_data })

...

{{ peer_data.pfs_group }}

推荐阅读