[英]Django: Display images in DataTables, ListView
I'd like to display a thumbnail image in a jQuery DataTables.我想在 jQuery 数据表中显示缩略图。
A similar post 1 shows that a js
render function needs to be added to the .DataTable
settings.类似的帖子1显示需要将
js
渲染 function 添加到.DataTable
设置中。
I'd like to implement this answer in a standard base case, using Django, class based ListView.我想在标准的基本情况下使用基于 Django、class 的 ListView 来实现这个答案。
My attempts creates an exception:我的尝试产生了一个例外:
'ImageListView' object has no attribute 'refresh_from_db'
'ImageListView' object 没有属性 'refresh_from_db'
Below is my setup下面是我的设置
$('#imagetable').DataTable({
"data": "img_url",
'render': function (data, type, full, meta) {
return '<img src="'+data+'" style="height:100px;width:100px;"/>';}
});
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')
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
<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>
Above produces an exception:上面产生了一个异常:
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'
I figured it out and share the answer as I struggled to find it myself.当我自己努力寻找答案时,我想通了并分享了答案。 Credit goes to @Mohit-Rustagi 's answer in the post here .
归功于@Mohit-Rustagi 在此处帖子中的回答。
It turned out that using class based ListView there is no need to serialise the data separately as the addition of the "render": function(data, type, row, meta)
together with columns
is enough.事实证明,使用基于 class 的 ListView 不需要单独序列化数据,因为添加
"render": function(data, type, row, meta)
和columns
就足够了。
I did following changes to above question:我对上述问题进行了以下更改:
$('#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;"/>';}
}]},
);
class ImageListView(ListView):
model = ProductImage
template_name = 'product/image_list.html'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.