错误:无法散列的类型:'dict' [英] Error: unhashable type: 'dict'
问题描述
我对Django有问题:我无法在表中显示mysql数据库中的数据.我看到错误异常值:不可哈希类型:'dict'"这是我的代码:views.py:
i have a problem with Django: I can't show the data from mysql database in the table. I see the error "Exception Value: unhashable type: 'dict'" This is my code: views.py:
List_of_date=El.objects.all()
return HttpResponse(template.render(context),args, {'List_of_date': List_of_date})
models.py:
models.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>
有人可以帮助我吗?
推荐答案
通常什么时候会出现无法散列的类型:"dict"
错误?
When do you generally get an unhashable type: 'dict'
error?
当您尝试使用字典作为键来在另一个字典中执行查找时,会出现此错误.
When you try to use a dictionary as a key to perform lookup in another dictionary, you get this error.
例如:
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'
为什么会出现此错误?
这是因为您创建 @所指出的实例时,将错误的参数传递给 HttpResponse
类弗朗西斯.
This is because you have passed wrong arguments to HttpResponse
class when creating its instance as pointed out by @Francis.
当您执行 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 响应对象的代码>.
When you do HttpResponse(template.render(context), args, {'List_of_date': List_of_date})
, then template.render(context)
becomes content
, args
becomes the content_type
and the dictionary {'List_of_date': List_of_date}
becomes the status
of the response object.
现在在内部,Django根据响应对象的 status
执行查找,以在响应对象上设置 reason_phrase
.由于 status
不是整数而是字典,因此会发生上述错误.
Now internally, Django performs a lookup based on the status
of the response object to set the reason_phrase
on response object. Since the status
is not an integer but a dictionary, the above error occurs.
解决方案:
您需要使用 render() @Daniel
快捷方式也可以很完美去做.
You need to use render()
shortcut provided by Django instead as @Daniel also mentioned which is perfect for what you are intending to do.
它将为您呈现模板,并使用 RequestContext
实例自动呈现模板.您可以执行以下操作:
It will render the template for you and automatically render the template with RequestContext
instance. You can do something like:
return render(template_name, {'List_of_date': List_of_date})
这篇关于错误:无法散列的类型:'dict'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!