2012-05-21 243 views
0

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

回答

4

你能做到彼此相關的幾個模型,並添加圖像在Django管理員一個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 

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

+0

你可以改變動態上傳ImageField的路徑嗎?這樣我可以將圖像上傳到/ images/country_name/state_name/city_name /例如? – HighLife

+1

是的,你可以。 upload_to可以是返回路徑的函數。看看這個: https://docs.djangoproject.com/en/1.4/ref/models/fields/#django.db.models.FileField.upload_to – Gerard