On the Django management site, there was a case that "If the image can be displayed on the list screen, it would be good work efficiency", but when I checked it, it was very easy, so I will record it as Tips.
I'm a little sorry that Qiita has only a little simple information, but Django is often filled with Stack Overflow even if you do a Google search, so there is little information that hits in Japanese, so it is useful for someone I think it may be posted.
For this article, we have confirmed the operation with Django 1.8.
I'll write it as a continuation of my book How to use ManyToManyField with Django's Admin.
As shown below, define a method (ʻadmin_og_image) with an arbitrary name that returns the file path of the image in models.py, and set ʻallow_tags = True
.
models.py
@@ -11,9 +11,18 @@ class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, blank=True, null=True)
meta = models.ManyToManyField('Tag')
-
+ og_image = models.ImageField(default='')
+
def __unicode__(self):
return self.title
+
+ def admin_og_image(self):
+ if self.og_image:
+ return '<img src="{}" style="width:100px;height:auto;">'.format(self.og_image)
+ else:
+ return 'no image'
+
+ admin_og_image.allow_tags = True
Then add the method name to list_display
in admin.py and you're done.
admin.py
@@ -3,7 +3,7 @@ from django.contrib import admin
from .models import Author, Article, Tag
class ArticleAdmin(admin.ModelAdmin):
- list_display = ('title', 'author', '_meta')
+ list_display = ('title', 'author', '_meta', 'admin_og_image')
In addition, it is also possible to write it completely with only admin.py, in which case it is OK if you write as follows.
models.py
@@ -11,9 +11,18 @@ class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, blank=True, null=True)
meta = models.ManyToManyField('Tag')
-
+ og_image = models.ImageField(default='')
+
admin.py
@@ -3,11 +3,19 @@ from django.contrib import admin
from .models import Author, Article, Tag
class ArticleAdmin(admin.ModelAdmin):
- list_display = ('title', 'author', '_meta')
+ list_display = ('title', 'author', '_meta', 'admin_og_image')
def _meta(self, row):
return ','.join([x.name for x in row.meta.all()])
+ def admin_og_image(self, row):
+ if row.og_image:
+ return '<img src="{}" style="width:100px;height:auto;">'.format(row.og_image)
+ else:
+ return 'no image'
+
+ admin_og_image.allow_tags = True
+
Recommended Posts