33 lines
1.3 KiB
Python
33 lines
1.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
|
|
|
|
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)
|
|
|
|
# Process submitted form
|
|
if request.method == 'POST':
|
|
# Get data from form
|
|
form_data = {attrib: request.form[attrib] for attrib in item_attributes}
|
|
try:
|
|
primary_attr = next((attrib_name for attrib_name, attrib in item_attributes.items() if attrib.primary), None)
|
|
except ValueError:
|
|
return render_template('create.html', item_attributes=item_attributes, exc=primary_attr)
|
|
|
|
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') |