HighLife
HighLife

Reputation: 4344

Uploading Images in Django Admin

I have a Django database full of cities. I'd like to use the Django admin panel to upload multiple pictures of each city to my server in some folder say /images/country_name/state/city/. This would probably be added to a city admin form, so images and information can all be edited on one page. I also need to select a primary image and convert it to a thumbnail so that it can be used in search results. What are good ways to implement this type of functionality? Are there good django addons that could help me out with these tasks?

Upvotes: 0

Views: 5932

Answers (1)

Gerard
Gerard

Reputation: 9408

you can do a couple models related to each other and add the image as a TabularInline in django-admin, like:

# models.py
class City(models.Model):
    # your fields

class CityImage(models.Model):
    city = models.ForeignKey('City', related_name='images')
    image = models.ImageField(upload_to=image_upload_path)

# admin.py
from django.contrib import admin
from myapp.models import City, CityImage


class CityImageInline(admin.TabularInline):
    model = CityImage


class CityAdmin(admin.ModelAdmin):
    inlines = [CityImageInline]


admin.site.register(City, CityAdmin)

As for the thumbnail, you would need in your City model a way to decide which of the related images you want to use as thumbnail and then do something like:

import Image
try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO
from django.core.files.base import ContentFile

# other imports and models

class City(models.Model):
    # your fields

    def get_thumbnail(self, thumb_size=None):
        # find a way to choose one of the uploaded images and
        # assign it to `chosen_image`.
        base = Image.open(StringIO(chosen_image.image.read()))  # get the image

        size = thumb_size
        if not thumb_size:
            # set a default thumbnail size if no `thumb_size` is given
            rate = 0.2  # 20% of the original size
            size = base.size
            size = (int(size[0] * rate), int(size[1] * rate))

        base.thumbnail(size)  # make the thumbnail
        thumbnail = StringIO()
        base.save(thumbnail, 'PNG')
        thumbnail = ContentFile(thumbnail.getvalue())  # turn the tumbnail to a "savable" object
        return thumbnail

I hope this comes in handy! :)

Upvotes: 5

Related Questions