首页 > 解决方案 > 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?

标签: pythondjangodjango-models

解决方案


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>

推荐阅读