40👍
What you can do is create a method in your TabularInline
subclass that returns the HTML you want, then use that method’s name in place of image
in ImageInline
.fields
:
from django.utils.safestring import mark_safe
class ImageInline(admin.TabularInline):
...
fields = (..., 'render_image')
readonly_fields = (..., 'render_image')
def render_image(self, obj):
return mark_safe("""<img src="/images/%s.jpg" />""" % obj.image)
20👍
According to current Django 1.2+ I got errors “Form does not have such field as render_image”. Solution is simple put the render_image function into model.Admin not in your inline form, second thing is fields and readonly_fields settings in your Inline form… So here You have what I’ve ended up with:
class OfferPropertyInline(admin.TabularInline):
model = OfferProperty
fields=('property_value',)
readonly_fields = ('property_value',)
class OfferAdmin(admin.ModelAdmin):
inlines = [
OfferPropertyInline
]
def property_value(self,obj):
return obj.get_value()
admin.site.register(Offer, OfferAdmin)
- [Django]-How can I get MINIO access and secret key?
- [Django]-Django 1.3.1 compilemessages. Error: sh: msgfmt: command not found
- [Django]-Itertools.groupby in a django template
3👍
Lechup’s answer does not work for me, I am using Django 1.11.7. I found this way to work around.
Let say I have 2 tables: Campaign and Article, one campaign has many articles. I want to show the articles when browsing a specific campaign.
Table Article has a column named score, which is a float. I want to round it up to 2 decimal places when viewing in Django admin.
This example shows how you can make a custom column for TabularInline in Django admin.
class Article(models.Model):
title = models.TextField(null=False)
url = models.TextField()
score = models.FloatField(null=True)
def __str__(self):
return self.title
def display_score(self):
if self.score:
return round(self.score, 2)
return self.score
display_score.short_description = 'Score'
class ArticleInline(admin.TabularInline):
model = Article
readonly_fields = ('title', 'url', 'display_score')
fields = ('title', 'url', 'display_score')
class CampaignAdmin(admin.ModelAdmin):
inlines = [ArticleInline]
admin.site.register(Campaign, CampaignAdmin)
- [Django]-Django-allauth: Linking multiple social accounts to a single user
- [Django]-How to use pdb.set_trace() in a Django unittest?
- [Django]-How to merge consecutive database migrations in django 1.9+?
0👍
@lechup correct except you need:
readonly_fields = ('mycustomfield',)
defined in the Inline for later versions of django (+1.4)
- [Django]-How to test auto_now_add in django
- [Django]-No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
- [Django]-Django staticfiles not found on Heroku (with whitenoise)