52 lines
2.3 KiB
Python
52 lines
2.3 KiB
Python
from flask import Blueprint, request, render_template, redirect
|
|
from definitions.models import Asset, db
|
|
from config import item_attributes
|
|
from sqlalchemy import exc # Import exc for database exceptions
|
|
from definitions.attribute import selectAttribute, intAttribute # Import attribute classes
|
|
|
|
addasset_bp = Blueprint('addasset', __name__)
|
|
|
|
@addasset_bp.route('/create/', methods=['GET', 'POST'])
|
|
def create():
|
|
if request.method == 'GET':
|
|
# Render the "add item" form
|
|
return render_template(
|
|
'create.html',
|
|
item_attributes=item_attributes,
|
|
isinstance=isinstance, # Pass isinstance to the template
|
|
hasattr=hasattr, # Pass hasattr to the template
|
|
selectAttribute=selectAttribute, # Pass selectAttribute to the template
|
|
intAttribute=intAttribute # Pass intAttribute to the template
|
|
)
|
|
|
|
# Process submitted form
|
|
if request.method == 'POST':
|
|
# Get data from form
|
|
form_data = {attrib.attrib_name: request.form[attrib.attrib_name] for attrib in item_attributes}
|
|
|
|
# Validate status (if it's an option field)
|
|
status_attrib = next((attrib for attrib in item_attributes if attrib.attrib_name == 'status'), None)
|
|
if status_attrib and isinstance(status_attrib, selectAttribute):
|
|
if form_data['status'] not in status_attrib.options:
|
|
return render_template('create.html', item_attributes=item_attributes, exc='status')
|
|
|
|
# Convert staffnum to int (if it's a number field)
|
|
staffnum_attrib = next((attrib for attrib in item_attributes if attrib.attrib_name == 'staffnum'), None)
|
|
if staffnum_attrib and isinstance(staffnum_attrib, intAttribute):
|
|
try:
|
|
form_data['staffnum'] = int(form_data['staffnum'])
|
|
except ValueError:
|
|
return render_template('create.html', item_attributes=item_attributes, exc='staffnum')
|
|
|
|
# Create the Asset object
|
|
item = Asset(**form_data)
|
|
|
|
try:
|
|
db.session.add(item)
|
|
db.session.commit()
|
|
except exc.IntegrityError:
|
|
return render_template('create.html', item_attributes=item_attributes, exc='integrity')
|
|
except exc.StatementError:
|
|
return render_template('create.html', item_attributes=item_attributes, exc='status')
|
|
|
|
return redirect('/viewall') |