当前,我正在Django中为CMS应用程序上传图片。现在,编写的代码可以做到这一点。
现在,我想在Heroku上部署它,因此我将图像存储在Amazon S3上。
models.py
def file_rename(instance, filename):
ext = filename.split('.')[-1]
count = Count.objects.get(pk=1)
ZSN = "ZT-WJ-" + str(count.jeans_count + 1)
filename = '{}.{}'.format(ZSN, ext)
return os.path.join('images', filename)
class Images(models.Model):
design_id = models.CharField(max_length=128)
file = models.ImageField(upload_to=file_rename)
cost_price = models.FloatField()
category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=False)
fabric = models.ForeignKey(Fabric, on_delete=models.CASCADE, blank=False)
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE, blank=False)
selling_price = models.FloatField()
aliveness = models.IntegerField(default=1)
date_added = models.DateTimeField(default=datetime.datetime.now)
group = models.ForeignKey(Group, on_delete=models.CASCADE, blank=False)
no_of_designs_or_colors = models.IntegerField(blank=False, null=True)
catalogue_name = models.CharField(max_length=50, null=True, blank=True)
visit_count = models.IntegerField(default=0)
set_sizes = models.ForeignKey(Sizes, on_delete=models.CASCADE, blank=False)
set_cat_id = models.IntegerField(default=1)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=False)
colours = models.CharField(max_length=128, null=True, blank=True)
def __unicode__(self):
return unicode(self.design_id)
在我的views.py
image.save()
image2 = Image.open('media/' + str(image.file))
#Do all the pre-processing
image2.save('media/' + str(image.file))
#Then transferring it to S3 using Boto
data = open('media/' + str(image.file), 'rb')
s3.Bucket('bucket_name').put_object(Key=str(image.file), Body=data)
要显示上传的图像, 我的views.py
def viewall(request):
categories = Category.objects.all()
images = Images.objects.all().order_by('-id')
return render(request, 'cms/view-all.html',{'images':images,'media_url':settings.MEDIA_URL,'categories':categories})
我的view-all.html
{% for category in categories %}
<br /><h3>{{ category.name }}</h3>
<div class="wrapper">
<div id="slider4" class="text-center">
{% for image in images %}
{% ifequal image.category category %}
<div class="container">
<img src="{{ image.file.url }}">
<div class="overlay">Category: {{ image.category }}<br />
Manufacturer: {{ image.manufacturer }}<br />
Location: {{ image.manufacturer.location }}<br />
Cost price: {{ image.cost_price }}<br />
Sales price: {{ image.selling_price }}<br />
{% if image.colours %}
Colors: {{ image.colours }}<br />
{% endif %}
</div>
<br />
</div>
{% endifequal %}
{% endfor %}
</div>
</div>
在此,我添加了一个悬停栏,其中包含图像的属性。当鼠标悬停在图像上时,它将显示。
现在,我还想显示已经上传的图像。为此,我必须从数据库中检索图像及其属性。但是数据库具有指向文件系统中图像的图像路径。
请帮助提供代码。应该非常感谢。
编辑:似乎我不能只更改存储在图像文件字段中的内容。我还需要更改MEDIA_URL和MEDIA_ROOT。
这是我的设置。py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
请同时建议对此进行适当的更改。