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>
Here I'm trying to upload multiple images but in view i'm getting lastly selected one image only. How to get all images and save all images. Help me in this problem.
You can create a separate image class with foreign key as Ads as below and call the images in your templates as object.image_set.all(), so that you can add any amount of images which inherit from your Ads model
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.