In django admin how do you access a function in a child model? -


i access thumbnail function of image model preview in tabularinline.

in admin.py

class blogwidgetcarouselinline(admin.tabularinline):     model = blogwidgetcarousel     = 0     readonly_fields = ('display_as', 'thumb', 'print_thumbs',)      def display_as(self, instance):         return instance.display()     display_as.allow_tags = true      def thumb(self, instance):         return instance.image.thumb() #does not work      def print_thumbs(self, instance):         return instance.print_thumb() #neither 

in models.py

class blogwidgetcarousel(models.model):     entry = models.textfield()     blog = models.foreignkey(blog, blank=true, null=true)     position = models.positivesmallintegerfield("position")     images = models.manytomanyfield("image")      class meta:         ordering = ('position', )      def display(self):         return self.entry     display.allow_tags = true      def print_thumb(self):         return self.images.thumb  class image(models.model):     title = models.charfield(max_length=60, blank=false, null=false)     image = models.imagefield(upload_to="images/")      def thumb(self):         return '<a href="{0}"><img src="{0}"></a>'.format(media_url + str(self.image))     thumb.allow_tags = true 

the images field on blogwidgetcarousel manytomanyfield, returns queryset of image objects.

so, first, need see if have image instances display, , grab first one, or whichever want use:

class image(models.model):     . . .      def thumb(self):         return '<a href="{0}"><img src="{0}"></a>'.format(self.image.url)   class blogwidgetcarouselinline(admin.tabularinline):  . . .      def thumb(self):         images = self.images.all()         if images:             return images[0].thumb()         return '' 

in example, empty string returned, return "default" thumbnail path. i'm not big fan of rendering html in python code, move portion template fragment:

from django.template.defaultfilters import mark_safe django.template.loader import render_to_string   class image(models.model)     . . .      def thumb(self):         return mark_safe(render_to_string('_thumb.html', {'image': images[0].image}))   # _thumb.html  <a href="{{ image.url }}"><img src="{{ image.url }}"></a> 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -