簡體   English   中英

在Django Admin中上傳圖片

[英]Uploading Images in Django Admin

我有一個充滿城市的Django數據庫。 我想使用Django管理面板將每個城市的多張圖片上傳到我的服務器的某個文件夾中,例如/ images / country_name / state / city /。 這可能會添加到城市管理表單中,因此圖像和信息都可以在一頁上進行編輯。 我還需要選擇一個主圖像並將其轉換為縮略圖,以便可以在搜索結果中使用它。 有什么好的方法可以實現這種功能? 有沒有好的django插件可以幫助我完成這些任務?

您可以建立相互關聯的幾個模型,並將圖像作為django-admin中的TabularInline添加,例如:

# 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)

至於縮略圖,您需要在City模型中確定要用作縮略圖的哪些相關圖像,然后執行以下操作:

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

我希望這會派上用場! :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM