Commit 48e5fd07 authored by Willard's avatar Willard

Implement FormView, rewrite new_dish using it

parent 121466d5
......@@ -3,30 +3,30 @@ import os.path
from canteeneo import app, db
from canteeneo.models import Stall, Dish
from canteeneo.forms import DishRegisterForm
from canteeneo.views import flash_form_errors, stall_validate, dish_validate
from canteeneo.views import flash_form_errors, stall_validate, dish_validate, FormView
from flask import render_template, redirect, url_for, request
from flask_login import login_required
from werkzeug.utils import secure_filename
@app.route('/stalls/<int:stall_id>/dishes/new', methods=['GET','POST'])
@login_required
@stall_validate
def new_dish(stall_id):
stall = Stall.query.get(stall_id)
form = DishRegisterForm()
if request.method == 'POST':
if form.validate():
class NewDishView(FormView):
decorators=[login_required, stall_validate]
def dispatch_request(self, stall_id):
self.stall = Stall.query.get(stall_id)
return FormView.dispatch_request(self, stall_id)
def render_post(self, stall_id):
filename = secure_filename(form.image.data.filename)
dish = Dish(form.name.data, form.description.data, form.price.data, stall.id, filename)
dish = Dish(form.name.data, form.description.data, form.price.data, self.stall.id, filename)
form.image.data.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
db.session.add(dish)
db.session.commit()
return redirect(url_for('view_stall', stall_id=stall.id))
else:
flash_form_errors(form)
return redirect(url_for('new_dish', stall_id=stall.id))
else:
return render_template('newdish.html', form=form, stall=stall)
def render_get(self, stall_id):
return render_template('newdish.html', form=self.get_form(), stall=self.stall)
def get_form(self):
return DishRegisterForm()
app.add_url_rule('/stalls/<int:stall_id>/dishes/new', view_func=NewDishView.as_view('new_dish'))
@app.route('/stalls/<int:stall_id>/dishes/<int:dish_id>', methods=["GET"])
@login_required
......
......@@ -2,10 +2,27 @@ import os.path
from functools import wraps
from canteeneo import app, login_manager, db
from flask import flash, redirect, render_template, request, url_for
from flask.views import View
from flask_login import login_required, login_user, logout_user, current_user
from forms import OwnerLoginForm, OwnerRegisterForm
from models import Owner, Stall, Dish
class FormView(View):
def dispatch_request(self, **kwargs):
form = self.get_form()
if request.method == 'POST':
if form.validate():
return self.render_post(**kwargs)
flash_form_errors(form)
elif request.method == 'GET':
return self.render_get(**kwargs)
def get_form(self):
raise NotImplementedError()
def render_post(self, **kwargs):
return ''
def render_get(self, **kwargs):
return ''
@app.route('/')
def index():
if current_user.is_authenticated:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment