from wtforms import SubmitField, StringField, HiddenField, SelectField, validators, Form from flask import request, render_template from __main__ import db, app, ma ################################################################################ # Class describing Rating in the database, and via sqlalchemy, connected to the DB as well ################################################################################ class Rating(db.Model): id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True) name = db.Column(db.String(50), unique=False, nullable=False) def __repr__(self): return "".format(self.id,self.name) ################################################################################ # Helper class that inherits a .dump() method to turn class Rating into json / useful in jinja2 ################################################################################ class RatingSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Rating ################################################################################ # Helper class that defines a form for rating, used to make html
, with field validation (via wtforms) ################################################################################ class RatingForm(Form): id = HiddenField() name = StringField('Name:', [validators.DataRequired()]) submit = SubmitField('Save' ) delete = SubmitField('Delete' ) ################################################################################ # Routes for rating data # # /ratings -> GET only -> prints out list of all ratings ################################################################################ @app.route("/ratings", methods=["GET"]) def ratings(): ratings = Rating.query.order_by('id').all() return render_template("ratings.html", ratings=ratings) ################################################################################ # /rating/ -> GET/POST(save or delete) -> shows/edits/delets a single # rating ################################################################################ @app.route("/rating/", methods=["GET", "POST"]) def rating(id): ### DDP: should this be request.form or request.values? alert="Success" rating_form = RatingForm(request.form) if request.method == 'POST' and rating_form.validate(): id = request.form['id'] rating = Rating.query.get(id) try: request.form['submit'] except: message="Sorry, Deleting unsupported at present" alert="Danger" else: rating.name = request.form['name'] db.session.commit() message="Successfully Updated Rating (id={})".format(id) else: rating = Rating.query.get(id) rating_form = RatingForm(request.values, obj=rating) message="" return render_template("rating.html", rating=rating, alert=alert, message=message, rating_form=rating_form)