javascript - Django:在 DataTables、ListView 中显示图像
问题描述
我想在 jQuery DataTables 中显示缩略图。
类似的帖子1显示js
需要将渲染功能添加到.DataTable
设置中。
我想在标准的基本案例中实现这个答案,使用 Django,基于类的 ListView。
我的尝试产生了一个例外:
'ImageListView' 对象没有属性 'refresh_from_db'
下面是我的设置
table_settings.js
$('#imagetable').DataTable({
"data": "img_url",
'render': function (data, type, full, meta) {
return '<img src="'+data+'" style="height:100px;width:100px;"/>';}
});
模型.py
class ProductImage(models.Model):
product_image_name = models.CharField(max_length=20)
product_image_description = models.TextField(max_length=255, null=True)
product_image = models.ImageField(default='product_image/default.jpg', upload_to='product_image')
视图.py
class ImageListView(LoginRequiredMixin, ListView):
model = ProductImage
template_name = 'product/image_list.html'
image_url = ProductImage.product_image
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
data['img_url'] = self.image_url
return data
表格元素(在 image_list.html 中)
<table id="imagetable">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
<tbody>
{% for object in object_list %}
<tr>
<td> {{ object.product_image_name }} </td>
<td> {{ object.product_image_description }} </td>
<td> {{ object.product_image }} </td>
</tr>
{% endfor %}
</tbody>
</table>
上面产生了一个异常:
AttributeError at /image/list/
'ImageListView' object has no attribute 'refresh_from_db'
Request Method: GET
Request URL: //localhost/image/list/
Django Version: 2.1.7
Exception Type: AttributeError
Exception Value:
'ImageListView' object has no attribute 'refresh_from_db'
解决方案
当我自己努力寻找答案时,我想通了并分享了答案。归功于@Mohit-Rustagi 在此处帖子中的回答。
事实证明,使用基于类的 ListView 不需要单独序列化数据,因为添加"render": function(data, type, row, meta)
withcolumns
就足够了。
我对上述问题进行了以下更改:
更改“table_settings.js”
$('#imagetable').DataTable({
"columns": [
{ "data": "product_image_name" },
{ "data": "product_image_description" },
{ "data": "product_image",
"render": function(data, type, row, meta) {
return '<img src="/media/'+data+'" style="height:100px;"/>';}
}]},
);
更改“views.py”
class ImageListView(ListView):
model = ProductImage
template_name = 'product/image_list.html'
推荐阅读
- vim-plugin - 无法将 ccls 语言服务器与 neovim native-lsp 一起使用
- typescript - 有没有办法根据打字稿中的修改属性来描述代理的类型
- python - 如何在python中获取值大于零的行的列
- react-native - 如何单击 Flatlist 中的项目以显示另一个组件而不在抽屉中显示它
- mysql - Mysql Parent Child 在孩子之后显示父母
- java - excel模板POI JAVA中的公式重新计算
- heroku - 我需要在我的设置文件中更改什么以使其连接到端口?
- google-sheets - 如何保护 Google 工作表:防止添加行的脚本
- javascript - 保存函数的状态
- java - Java QuickSort 算法,跟踪左右元素和枢轴