[英]Error: unhashable type: 'dict'
我有一个 Django 问题:我无法在表中显示来自 mysql 数据库的数据。 我看到错误“异常值:不可哈希类型:'dict'”这是我的代码:views.py:
List_of_date=El.objects.all()
return HttpResponse(template.render(context),args, {'List_of_date': List_of_date})
模型.py:
class El(models.Model):
id_ch=models.IntegerField()
TXT = models.CharField(max_length=200)
模板:
<table>
<thead>
<tr>
<th>№</th>
<th>Text</th>
</tr>
</thead>
<tbody>
{% for i in List_of_date %}
<tr>
<td class="center">{{ i.id_ch }}</td>
<td class="center">{{ i.TXT }}</td>
</tr>
{% endfor %}
</tbody>
</table>
有谁能够帮助我?
您将错误的参数传递给 HttpResponse 构造函数签名是
HttpResponse.__init__(content='', content_type=None, status=200, reason=None, charset=None)
我认为您想使用{'List_of_date': List_of_date}
作为模板渲染的上下文。 所以你宁愿调用类似的东西(我不知道你的 args 变量是什么)
return HttpResponse(template.render(Context({'List_of_date': List_of_date})))
你通常什么时候会得到一个unhashable type: 'dict'
错误?
当您尝试使用字典作为键在另一个字典中执行查找时,您会收到此错误。
例如:
In [1]: d1 = {'a':1, 'b':2}
In [2]: d2 = {'c':3}
In [3]: d2[d1] # perform lookup with key as dictionary 'd1'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-163d2a314f4b> in <module>()
----> 1 d2[d1]
TypeError: unhashable type: 'dict'
为什么会出现这个错误?
这是因为如@Francis所指出的那样,您在创建其实例时向HttpResponse
类传递了错误的参数。
当你做HttpResponse(template.render(context), args, {'List_of_date': List_of_date})
,然后template.render(context)
变成content
, args
变成content_type
和字典{'List_of_date': List_of_date}
变成status
响应对象的。
现在在内部,Django 根据响应对象的status
执行查找,以在响应对象上设置reason_phrase
。 由于status
不是整数而是字典,因此出现上述错误。
解决方案:
您需要使用 Django 提供的render()
快捷方式,因为@Daniel也提到这非常适合您打算做的事情。
它将为您呈现模板并使用RequestContext
实例自动呈现模板。 您可以执行以下操作:
return render(template_name, {'List_of_date': List_of_date})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.