python - 无法在 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']'
我做错了什么??
解决方案
问题在于它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 }}
推荐阅读
- javascript - 从 useEffect 返回的数据无限滚动/错误
- java - 试图将 Card 对象传递给 ArrayList
- java - 通过循环 arraylist 来填充 setter
- enums - 如何在函数中增加传递的枚举?
- python - 出现“不支持解码 str”错误
- python - 上传到 s3 后从本地服务器删除文件
- java - 在 PostgreSql 中批量更新或删除哪个更高效?
- typescript - Typescript 的复杂泛型类型
- python - /lib64/libc.so.6:未找到版本“GLIBC_2.14” - 使用 pyinstaller 构建应用程序时出错
- mysql - Sqoop 根据行键连接列值