我想使用Django构建一个图库。当然,每张图片都是一个帖子。现在,我不想独立上传每个图像。我想将它们全部压缩并在Django管理页面上传,也许创建某种触发器:
Django有可能吗?你最好的方法是什么?我会感激任何帮助,我对Django很新(比如5小时新)
答案 0 :(得分:1)
这是从上传的ZIP文件中提取文件的代码:
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius = 6371;// radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
}
答案 1 :(得分:1)
是的,这是可能的。这是一个广泛的大纲,完全受Mezzanine如何实现这一点的启发。
首先定义一个用于接受zip文件的字段:
class BaseGallery(models.Model):
zip_import = models.FileField(blank=True, upload_to=upload_to("galleries")
然后你有一个单独的模型,它是外键输入你的父模型。在此示例中,父模型为BaseGallery
,图像模型为GalleryImage
:
class GalleryImage(Orderable):
gallery = models.ForeignKey(Gallery, related_name="images")
file = models.ImageField(upload_to="galleries")
然后在您的模型的save
方法中,您可以提取此zip文件并保存单个图像:
from django.core.files import ContentFile
from django.conf import settings
from zipfile import ZipFile
def save(self, delete_zip_import=True, *args, **kwargs):
"""
If a zip file is uploaded, extract any images from it and add
them to the gallery, before removing the zip file.
"""
super(BaseGallery, self).save(*args, **kwargs)
if self.zip_import:
zip_file = ZipFile(self.zip_import)
for name in zip_file.namelist():
data = zip_file.read(name)
try:
from PIL import Image
image = Image.open(BytesIO(data))
image.load()
image = Image.open(BytesIO(data))
image.verify()
except ImportError:
pass
except:
continue
name = os.path.split(name)[1]
# You now have an image which you can save
path = os.path.join(settings.MEDIA_ROOT, "galleries",
native(str(name, errors="ignore")))
saved_path = default_storage.save(path, ContentFile(data))
self.images.create(file=saved_path)
if delete_zip_import:
zip_file.close()
self.zip_import.delete(save=True)
注意,实际保存图像的位已经简化了,如果你查看我链接的源代码,那么处理unicode文件名等需要更多的jiggery-pokery。
另请注意,Mezzanine使用自己的FileField
,这与Django的FileField
不同。我试图在上面的例子中重构这个。