Thursday, January 24, 2019

storing multiple images in python django

While storing image provided from template , a bit different scenario occurs which we will discuss below:

lets see create.html first:


       <label>Image Title</label>:<input class="form-control mr-sm-2" value="{{item.title}}" type="text"
                            name="title" placeholder="Title" required><br>

                        <div class="form-group">
                            <label for="image">Image</label>
                            <input type="file" class="form-control" name="image" id="image" multiple value="">
                        </div>

<div> <input type=text value="normaldata" name="staticdatas"></div>

here lets say image is multiple field and other are statuc field now,
on the views where we used to store data :

def store(request):
        if request.method=='POST':
                form=HotelGalleryForm(request.POST or None,request.FILES)
                if form.is_valid():
                        form=form.save(commit=False)    
                        images=request.FILES.getlist('image')
             
                        for img in images:
                                alldata=HotelGallery()
                                alldata.image=img
                                alldata.staticdatas=form.staticdatas
                                alldata.title=form.title
                                alldata.save()

                           
                        return redirect('hotel:hotelgallery')

                else:

                        return HttpResponse("KAAM vayena")   

it will sttore each image with static data in loop in database and will return to index page 


No comments:

Post a Comment