def add_article(): """Adds new clothing article and redirects to the previous category page.""" category_id = request.form.get('category') description = request.form.get('article-description') file = request.files['article-image-upload'] tag_ids = request.form.getlist('article-tags') new_tag_string = request.form.get('new-tags') purchase_price = request.form.get('purchase-price') category = Category.query.get(category_id) if not allowed_file(file.filename): flash(f'File extension .{file.filename.rsplit(".", 1)[1]} not allowed') if file and allowed_file(file.filename): # Sanitizes user input filename = secure_filename(file.filename) # Cloudinary upload function: 1) folders by user and category name, # 2) unique filename is true, # 3) use cloudinary's AI to remove background # ^ (commented out b/c paid service) upload_file = upload( file, folder=f"user/{session['user_email']}/{category.name}", unique_filename=1, # background_removal = "cloudinary_ai", ) # For purchase_price, an empty string not ok, but okay to pass None new_article = Article(user_id=session['user_id'], category_id=category_id, image=upload_file['secure_url'], description=description, purchase_price=purchase_price or None) all_tags = [] for tag_id in tag_ids: all_tags.append(Tag.query.filter_by(tag_id=tag_id).one()) # Any newly created tags should be added to this as well all_tags += Tag.parse_str_to_tag(new_tag_string, session['user_id']) # Then create all the tag relationships for tag in all_tags: new_article.add_tag(tag) db.session.add(new_article) db.session.commit() flash(f"Created new item in {category.name}") return redirect(f'/categories/{category_id}')