python - How to allow more than one image upload on django?
问题描述
Currently I have a pictures model, that allows an image upload per class product (Foreign key).
However I would like to upload more than one image per product
Below shows my models.py for Class picture.
def get_image_filename(instance,filename):
id = instance.product.id
return "picture_image/%s" % (id)
def path_and_rename(instance, filename):
upload_to = 'images'
ext = filename.split('.'[-1])
if instance.pk:
filename = '{}.{}'.format(instance.pk, ext)
else:
filename = '{}.{}'.format(uuid4().hex, ext)
return os.path.join(upload_to, filename)
class Picture(models.Model):
product_pic = models.ImageField(null=True, blank=True,upload_to=path_and_rename)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL )
date_created = models.DateTimeField(auto_now_add=True, null=True)
How does one allow more than one image upload on django?
解决方案
How does one allow more than one image upload on django?
You already can. Indeed, you can construct multiple Picture
objects for the same Product
. For example:
myproduct = Product.objects.first()
Picture.objects.create(product=my_product, product_pic=request.FILES['image1'])
Picture.objects.create(product=my_product, product_pic=request.FILES['image2'])
Here we thus construct two Picture
objects that refer to the same Product
.
You can make use of formsets to render the form for a Picture
multiple times. For example:
from django.forms import inlineformset_factory
from django.shortcuts import redirect
from app.models import Product, Picture
def my_view(request, product_pk):
PictureFormSet = inlineformset_factory(Product, Picture, fields=('product_pic',))
product = Author.objects.get(pk=product_pk)
if request.method == 'POST':
formset = PictureFormSet(request.POST, request.FILES, instance=product)
if formset.is_valid():
formset.save()
return redirect('name-of-some-view')
else:
formset = PictureFormSet(instance=product)
return render(request, 'some_template.html', {'formset': formset})
and in your template you then render this with:
<form enctype="multipart/form-data" method="post" action="{% url 'name-of-view' product_pk=formset.instance.pk %}">
{% csrf_token %}
{{ formset }}
</form>
推荐阅读
- javascript - 谁能解释为什么我得到一个 typeError 指出“this.draw 不是 ballFunction.move 的函数
- apache - 安装和升级帮助 安装程序无法创建数据目录(/var/www/moodledata)
- python-3.x - 将值插入字典列表
- python - 扩展 djoser 登录方法以获取用户角色
- python - 如何跨行从html中获取文本
- c++ - 将 std::web_view 工具引入标准有什么好处?
- jenkins - 如何将上一步(groovy 代码)的结果数据传递到可编辑的电子邮件通知步骤?
- r - 在 r 中,将数据框的一列转换为没有“未列出”且具有动态名称的向量
- php - PHP如何有序打印节点值XML
- javascript - 如何在 VueTestUtils / Jest 中模拟 Web API?