makes the name of a consumable unique

makes the column unique and extends the create form to respect the
uniqueness.
This commit is contained in:
Joachim Lusiardi 2016-06-27 19:48:04 +02:00
parent 90639a757d
commit 5e24b9779e
2 changed files with 15 additions and 3 deletions

View File

@ -9,6 +9,7 @@ from flask.ext.security import Security, SQLAlchemyUserDatastore, \
from flask.ext.security import user_registered from flask.ext.security import user_registered
from flask_security.core import current_user from flask_security.core import current_user
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
from flask.ext.security.forms import LoginForm from flask.ext.security.forms import LoginForm
app = Flask(__name__) app = Flask(__name__)
@ -307,11 +308,22 @@ def get_admin_page():
def create_consumable(): def create_consumable():
form = CreateConsumableForm() 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(): if form.validate_on_submit():
new_consumable = Consumable(form.name.data, form.unit.data) new_consumable = Consumable(form.name.data, form.unit.data)
db.session.add(new_consumable) db.session.add(new_consumable)
db.session.commit() try:
tools.db_log_add(new_consumable) 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 redirect(url_for('get_admin_page'))
return render_template('createConsumableForm.html', form=form) return render_template('createConsumableForm.html', form=form)

View File

@ -83,7 +83,7 @@ class Pitstop(db.Model):
class Consumable(db.Model): class Consumable(db.Model):
id = db.Column(db.Integer, primary_key=True) 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)) unit = db.Column(db.String(255))
def __init__(self, name, unit): def __init__(self, name, unit):