如何在Django中上传多张图片

时间:2019-11-20 11:25:41

标签: django django-models django-forms django-templates

models.py

from django.db import models

class Ads(models.Model):
    business_id = models.CharField(max_length=20, blank=True, null=True)
    description = models.CharField(max_length=100, blank=True, null=True)
    image = models.ImageField(upload_to='images', blank=True, null=True)

forms.py

from django import forms
from .models import Ads

class AdsForm(forms.Form):

    class Meta:
        model = Ads
        fields = '__all__'

view.py

from .models import Ads
from .forms import AdsForm
from django.core.files.storage import FileSystemStorage 

def ads_view(request):
    if request.method == 'POST':
        form = AdsForm(request.POST, request.FILES)
        if form.is_valid():
            business_id = request.POST.get('business_id')
            description = request.POST.get('description')
            image = request.FILES['image']
            print(business_id)
            print(description)
            print(image)
            file_storage = FileSystemStorage()
            ads_obj = Ads(business_id=business_id, description=description, image=file_storage.save(image.name, image))
            ads_obj.save()
            return redirect('/ads/')
    else:
        form = AdsForm()
        return render(request, 'ads/myads.html', {'form': form})

myads.html

<form action="#" method="post" enctype="multipart/form-data">
    <input type="text" name="business_id" class="form-control form-control" id="colFormLabelSm" placeholder="">
    <textarea name="description" class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
    <input type="file" name="image" class="form-control" id="exampleFormControlInput1" multiple>
    <button type="submit" class="btn btn-primary mt-5">Submit</button>
</form>

在这里,我尝试上传多张图片,但鉴于我最后只选择了一张图片。如何获取所有图像并保存所有图像。帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

您可以如下创建一个带有外键的单独图像类作为Ads,并在模板中将这些图像称为object.image_set.all(),以便您可以添加从Ads模型继承的任意数量的图像

class Ads(models.Model):
    business_id = models.CharField(max_length=20, blank=True, null=True)
    description = models.CharField(max_length=100, blank=True, null=True)

class Image(models.Model):
    ads = models.ForeignKey(Ads, ....)
    image = models.ImageField(upload_to='images', blank=True, null=True)