Answer the question
In order to leave comments, you need to log in
How to create a model attribute in Django without adding a field to the database?
I have an Article model defined in models.py
class Article(models.Model):
title = models.CharField(max_length=256)
slug = models.SlugField(max_length=256)
short_content = RichTextField(config_name='awesome_ckeditor')
full_content = RichTextField(config_name='awesome_ckeditor')
cover = models.ImageField(blank=True, upload_to='uploaded_images')
cropping = ImageRatioField('cover', '200x200')
show = models.BooleanField(default=0)
visits = models.BooleanField(default=0)
Answer the question
In order to leave comments, you need to log in
You can use either property for this :
import os
from django.db import models
class Article(models.Model):
title = models.CharField(
max_length=200,
)
image = models.ImageField(
blank=True,
upload_to='images',
)
@property
def thumbnail(self):
if self.image:
path, filename = os.path.split(self.image.url)
name, ext = os.path.splitext(filename)
filename = 'prefix_' + name + '_suffix' + ext
return os.path.join(path, filename)
import os
from django.contrib import admin
from django.utils.html import format_html
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = (
'title',
'get_thumbnail',
)
fields = (
'title',
'get_thumbnail',
)
readonly_fields = (
'get_thumbnail',
)
def get_thumbnail(self, obj):
if obj.image:
path, filename = os.path.split(self.image.url)
name, ext = os.path.splitext(filename)
filename = 'prefix_' + name + '_suffix' + ext
return format_html('<img src="{}">', os.path.join(path, filename))
get_thumbnail.short_description = 'Thumbnail'
get_logo.admin_order_field = 'image'
import os
from django.contrib import admin
from django.utils.html import format_html
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = (
'title',
'get_thumbnail',
)
fields = (
'title',
'get_thumbnail',
)
readonly_fields = (
'get_thumbnail',
)
def get_thumbnail(self, obj):
url = obj.thumbnail
return format_html('<img src="{}">', url) if url else ''
get_thumbnail.short_description = 'Thumbnail'
get_logo.admin_order_field = 'image'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question