#3 Create product form made, data is processed on the backend. Image data not currently saved

This commit is contained in:
2024-01-19 13:31:06 +00:00
parent b821050869
commit 98a17bdc43
3 changed files with 64 additions and 6 deletions

View File

@ -1,10 +1,21 @@
from flask import Blueprint
from flask import render_template, session, flash, request, redirect
from models.products.product import Product
from controllers.database.product import ProductController
from controllers.database.category import CategoryController
from controllers.database.user import UserController
from datetime import datetime
from werkzeug import secure_filename
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
blueprint = Blueprint("products", __name__, url_prefix="/products")
# Global context to enable the categories to be accessed
@ -54,7 +65,7 @@ def id(id: int):
# Launches the page to add a new product to the site
@blueprint.route('/add')
def add_product():
def display_add_product():
user_id = session.get('user_id')
# User must be logged in to view this page
@ -69,3 +80,47 @@ def add_product():
return redirect('/')
return render_template('index.html', content='new_product.html')
# Processes a request to add a new product to the site
@blueprint.post('/add')
def add_product():
user_id = session.get('user_id')
# User must be logged in to view this page
if user_id == None:
flash("Please Login to view this page")
return redirect('/login', code=302)
db = UserController()
user = db.read_id(user_id)
if user == None or user.role != "Seller":
flash("You must be logged in as a Seller to perform this action")
return redirect('/', code=302)
file = request.files.get('image')
# Ensure that the correct file type is uploaded
if file == None OR NOT allowed_file(file.filename):
flash("Invalid File Uploaded")
return redirect("/add")
# Create the product object and push to database
filename = secure_filename(file.filename)
file.save(os.path.join('static/assets/img/products/', secure_filename))
file.save
product = Product(
request.form.get('name'),
filename
request.form.get('description'),
request.form.get('cost'),
request.form.get('category'),
user.id,
datetime.now(),
request.form.get('quantity')
)
db = ProductController()
db.create(product)
return render_template('index.html', content='new_product.html')