upload multiple images in flask and wtforms

29 Views Asked by At

I am new in Flask and I am trying to upload multiple images, I have an issue in the database as all images are uploaded in a folder inside my app. but the problem is with the database as it only saves last image

here is my code :

@presentation.route('/presentation/add',methods=['GET','POST'])
@login_required
def add():
    #intiat instans from validaition class
    form = addPresentaion()
    if form.validate_on_submit():
        presentation =Presentaions(
            title  = form.title.data,
            slug   =form.slug.data,
            description =form.description.data,
            ) 
        presentation.author=current_user
        if form.image.data :
            pic = uploadMainPresntaionImage(form.image.data,form.title.data)
            presentation.image=pic
            
        presentation.last_updated_at = datetime.datetime.now()
        presentation.created_at      = datetime.datetime.now() 
        presentation.last_updated_by =  current_user.id
        db.session.add(presentation)
        db.session.commit()
        last_inserted_id = presentation.id
        if last_inserted_id:
            path = current_app.root_path+'\static\pres_images\\'+str(current_user.id)+'\\'
            folder =os.path.join(path,str(last_inserted_id))
            os.makedirs(folder)
        #add presntaion images
        presntion_image = PresntaionImages(
            pres_author =presentation 
        ) 
        
        presntion_image.image_name = uploadPresentaionImages(form.images.data,current_user.id,last_inserted_id)  
        db.session.add(presntion_image)
        db.session.commit()     
    
        flash('Data Added Sucsessfully ...','success')
        return redirect(url_for('presentation.add'))
        exit()
    elif request.method == "GET":
        form.title.data = form.title.data 
        form.slug.data  = form.slug.data 
        form.description.data = form.description.data 
    #create user object
   
    pagetitle = "Presenter X | Add Presentaion"
    return render_template('presentaion_template/add.html',form=form,pagetitle=pagetitle) 

my uploader function is :

 defuploadPresentaionImages(pic_upload,user_id,presntaion_id):
        count=1
        for img in pic_upload:
            filename = img.filename
            ext_type = filename.split('.')[-1]
            storage_filename = str(count)+'.'+ext_type
            filepath = os.path.join(current_app.root_path,'static\pres_images\\'+str(user_id)+'\\'+str(presntaion_id),storage_filename)
            pic = Image.open(img)
            pic.save(filepath)
            count+=1
        return storage_filename

any help please

0

There are 0 best solutions below