Commit 5a012c2e authored by Francesca Sargent 's avatar Francesca Sargent
Browse files

Recipe steps, updating recipe steps

parent dc7ec48e
......@@ -53,8 +53,6 @@ class EditProfileAdminForm(Form):
raise ValidationError('Username already in use.')
class RecipeStepForm(Form):
# step_id = IntegerField('Step Number', [validators.NumberRange(min=0, max=10)])
step_text = TextAreaField()
def __init__(self, *args, **kwargs):
......@@ -63,12 +61,6 @@ class RecipeStepForm(Form):
class SplitStringField(StringField):
def _value(self):
if self.data:
return u', '.join(self.data)
else:
return u''
def process_formdata(self, valuelist):
if valuelist:
self.data = [x.strip() for x in valuelist[0].split(',')]
......@@ -79,9 +71,9 @@ class SplitStringField(StringField):
class RecipeForm(Form):
name = StringField('Recipe Name', validators=[Required(), Length(0, 64)])
description = PageDownField('Recipe Description')
steps = FieldList(FormField(RecipeStepForm), min_entries=10)
cuisines = SplitStringField()
methods = SplitStringField()
steps = FieldList(FormField(RecipeStepForm), min_entries=1)
cuisines = SplitStringField(validators=[Required()])
methods = SplitStringField(validators=[Required()])
submit = SubmitField('Submit')
def __init__(self, *args, **kwargs):
......@@ -89,12 +81,25 @@ class RecipeForm(Form):
self.cuisines.choices = [(cuisine.id, cuisine.name)
for cuisine in Cuisine.query.order_by(Cuisine.name).all()]
class RecipeEditForm(Form):
name = StringField('Recipe Name', validators=[Required(), Length(0, 64)])
description = PageDownField('Recipe Description')
steps = FieldList(FormField(RecipeStepForm), min_entries=1)
cuisines = SplitStringField(validators=[Required()])
methods = SplitStringField(validators=[Required()])
submit = SubmitField('Submit')
def __init__(self, *args, **kwargs):
super(RecipeEditForm, self).__init__(*args, **kwargs)
self.cuisines.choices = [(cuisine.id, cuisine.name)
for cuisine in Cuisine.query.order_by(Cuisine.name).all()]
class CuisineForm(Form):
name = TextAreaField("Cuisine Name", validators=[Required()])
description = PageDownField("Cuisine Description", validators=[Required()])
methods = SplitStringField()
methods = SplitStringField(validators=[Required()])
submit = SubmitField('Submit')
def __init__(self, *args, **kwargs):
......@@ -106,7 +111,7 @@ class MethodForm(Form):
name = StringField("Method Name", validators=[Required()])
description = PageDownField('Method Description')
method_text = PageDownField('Method Instructions')
cuisines = SplitStringField()
cuisines = SplitStringField(validators=[Required()])
submit = SubmitField('Submit')
def __init__(self, *args, **kwargs):
......
......@@ -2,8 +2,14 @@ from flask import render_template, redirect, url_for, abort, flash, request,\
current_app, make_response, jsonify
from flask.ext.login import login_required, current_user
from . import main
import wtforms
from wtforms import StringField, TextAreaField, BooleanField, SelectField,\
SubmitField, FormField, IntegerField, FloatField, FieldList, Field
from wtforms.validators import Required, Length, Email, Regexp, Optional
from wtforms import ValidationError, validators, widgets
from flask.ext.pagedown.fields import PageDownField
from .forms import EditProfileForm, EditProfileAdminForm, RecipeForm,\
CommentForm, CuisineForm, RecipeStepForm, MethodForm
CommentForm, CuisineForm, RecipeStepForm, MethodForm, RecipeEditForm, SplitStringField
from .. import db
from ..models import Permission, Role, User, Recipe, Comment, Cuisine, RecipeSteps, Method
from ..decorators import admin_required, permission_required
......@@ -25,6 +31,15 @@ def addMethod(name):
return methods
def returnListed(subcats):
lists = []
for subcat in subcats:
lists.append(subcat.name)
lists = ', '.join(lists)
return lists
@main.route('/')
def index():
page = request.args.get('page', 1, type=int)
......@@ -127,9 +142,23 @@ def poststuff(type):
else:
recipe.methods = addCuisine(form.methods.data)
for index,step_entry in enumerate(form.steps.entries):
try:
step = RecipeSteps()
step.id = (str(recipe.id)+str(index))
step.step_id = index
step.step_text = step_entry.step_text.data
step.recipe_id = recipe.id
db.session.add(step)
except:
print "Query error"
recipe.author = current_user._get_current_object()
db.session.add(recipe)
flash('Your recipe has been added.')
return redirect(url_for('.index'))
if type == 'cuisine':
......@@ -156,6 +185,7 @@ def poststuff(type):
db.session.add(cuisine)
db.session.flush()
flash('Your cuisine has been added.')
return redirect(url_for('.index'))
if type == 'method':
......@@ -183,6 +213,7 @@ def poststuff(type):
db.session.add(method)
db.session.flush()
flash('Your method has been added.')
return redirect(url_for('.index'))
db.session.commit()
......@@ -361,10 +392,21 @@ def method(id):
def editrecipe(id):
db.session.autoflush = True
recipe = Recipe.query.get_or_404(id)
if current_user != recipe.author and \
not current_user.can(Permission.ADMINISTER):
abort(403)
form = RecipeForm()
class F(RecipeEditForm):
name = StringField('Recipe Name', validators=[Required(), Length(0, 64)])
description = PageDownField('Recipe Description')
steps = FieldList(FormField(RecipeStepForm), min_entries=recipe.steps.count())
cuisines = SplitStringField(validators=[Required()])
methods = SplitStringField(validators=[Required()])
submit = SubmitField('Submit')
form = F()
if form.validate_on_submit():
......@@ -379,25 +421,49 @@ def editrecipe(id):
recipe.methods.extend(method)
recipe.name = form.name.data
recipe.description = form.description.data
# recipe.steps = [RecipeSteps(step_id = form.steps.step_id.data, step_text = form.steps.step_text.data)]
for index,step_entry in enumerate(form.steps.entries):
step = RecipeSteps()
step.step_id = index
step.step_text = step_entry.step_text.data
# step.recipe_name = [Recipe.query.filter_by(name=form.name.data).first()]
db.session.merge(step)
db.session.flush()
step_id = (str(recipe.id)+str(index))
try:
step_id = (str(recipe.id)+str(index))
step_exist = RecipeSteps.query.get(step_id)
if step_exist != None:
step = RecipeSteps.query.get(step_id)
else:
step = RecipeSteps()
step.id = (str(recipe.id)+str(index))
step.step_id = index
step.step_text = step_entry.step_text.data
step.recipe_id = recipe.id
db.session.add(step)
except:
print "Query error"
db.session.add(recipe)
flash('The recipe has been updated.')
return redirect(url_for('.recipe', id=recipe.id))
form.description.data = recipe.description
form.name.data = recipe.name
form.cuisines.data = returnListed(recipe.cuisines)
form.methods.data = returnListed(recipe.methods)
for i in range(0, recipe.steps.count()):
form.steps[i].step_text.data = recipe.steps[i].step_text
form.steps.choices = {'a' : 'b'}
return render_template('edit_recipe.html', form=form)
......@@ -425,6 +491,8 @@ def editmethod(id):
form.name.data = method.name
form.description.data = method.description
form.method_text.data = method.method_text
form.cuisines.data = returnListed(method.cuisines)
return render_template('edit_recipe.html', form=form)
@main.route('/cuisine/<int:id>/edit', methods=['GET', 'POST'])
......@@ -450,7 +518,7 @@ def editcuisine(id):
return redirect(url_for('.cuisine', id=cuisine.id))
form.name.data = cuisine.name
form.description.data = cuisine.description
form.methods.data = ''
form.methods.data = returnListed(cuisine.methods)
return render_template('edit_recipe.html', form=form)
......
......@@ -319,7 +319,7 @@ db.event.listen(Recipe.body, 'set', Recipe.on_changed_body)
class RecipeSteps(db.Model):
__tablename__ = 'recipesteps'
id = db.Column(db.Integer, primary_key=True)
recipe_name = db.Column(db.Integer, db.ForeignKey('recipes.id'))
recipe_id = db.Column(db.Integer, db.ForeignKey('recipes.id'))
step_id = db.Column(db.Integer)
step_text = db.Column(db.Text)
......@@ -335,6 +335,7 @@ class Cuisine(db.Model):
comments = db.relationship('Comment', backref='cuisine', lazy='dynamic')
class Method(db.Model):
__tablename__='methods'
id = db.Column(db.Integer, primary_key=True)
......
......@@ -135,3 +135,17 @@ ul.nav.navbar-nav a {
margin: 5px;
font-size: 1.2em;
}
ul#steps.form-control {
display: block;
list-style: none;
float: left;
height: auto;
}
#add_another_button {
background: #e74c3c;
color: #fff;
margin: 5px;
padding: 5px;
}
......@@ -137,7 +137,31 @@
alert(request.responseText);
}
});
$('textarea#steps-0-step_text').after('<div id="add_another_button">Add</div>')
$('#add_another_button').click(function () {
clone_field_list('li:last');
});
function clone_field_list(selector) {
var new_element = $(selector).clone(true);
var elem_id = new_element.find(':input')[0].id;
var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1;
new_element.find(':input').each(function() {
var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + elem_num + '-');
$(this).attr({'name': id, 'id': id}).val('').removeAttr('checked');
});
new_element.find('label').each(function() {
var new_for = $(this).attr('for').replace('-' + (elem_num - 1) + '-', '-' + elem_num + '-');
$(this).attr('for', new_for);
});
$(selector).after(new_element);
}
</script>
{{ moment.include_moment() }}
{% endblock %}
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