diff --git a/app/rollerverbrauch/__init__.py b/app/rollerverbrauch/__init__.py index 9b7bcb6..46bd409 100644 --- a/app/rollerverbrauch/__init__.py +++ b/app/rollerverbrauch/__init__.py @@ -9,6 +9,7 @@ from flask.ext.security import Security, SQLAlchemyUserDatastore, \ from flask.ext.security import user_registered from flask_security.core import current_user from flask_sqlalchemy import SQLAlchemy +from sqlalchemy.exc import IntegrityError from flask.ext.security.forms import LoginForm app = Flask(__name__) @@ -307,11 +308,22 @@ def get_admin_page(): def create_consumable(): form = CreateConsumableForm() + # preinitialize the defaults with potentially existing values from a try before + if form.name.data is not None: + form.name.default = form.name.data + if form.unit.data is not None: + form.unit.default = form.unit.data + if form.validate_on_submit(): new_consumable = Consumable(form.name.data, form.unit.data) db.session.add(new_consumable) - db.session.commit() - tools.db_log_add(new_consumable) + try: + db.session.commit() + tools.db_log_add(new_consumable) + except IntegrityError: + db.session.rollback() + form.name.errors.append('"%s" is not unique.' % (form.name.data)) + return render_template('createConsumableForm.html', form=form) return redirect(url_for('get_admin_page')) return render_template('createConsumableForm.html', form=form) diff --git a/app/rollerverbrauch/entities.py b/app/rollerverbrauch/entities.py index 83e5cd7..c0b066f 100644 --- a/app/rollerverbrauch/entities.py +++ b/app/rollerverbrauch/entities.py @@ -83,7 +83,7 @@ class Pitstop(db.Model): class Consumable(db.Model): id = db.Column(db.Integer, primary_key=True) - name = db.Column(db.String(255)) + name = db.Column(db.String(255), unique=True) unit = db.Column(db.String(255)) def __init__(self, name, unit):