错误:不可用类型:' dict'

时间:2015-08-30 10:53:34

标签: python mysql django

我有Django的问题: 我无法在表格中显示mysql数据库中的数据。我看到了错误"异常值:不可用的类型:' dict'" 这是我的代码: views.py:

List_of_date=El.objects.all()
return HttpResponse(template.render(context),args, {'List_of_date': List_of_date})

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>

有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

您将错误的参数传递给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})))

答案 1 :(得分:1)

您何时会出现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)变为contentargs变为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})