2012-05-21 152 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