Chris Grubbs avatar Chris Grubbs committed 1e00e0e

view for new recipe - maybe need to merge new/edit pages?

Comments (0)

Files changed (7)

phlombay/recipes/urls.py

     url(r'^my-page/$', 'my_page', name='my_page'),
     (r'^new/$','new'),
     (r'^edit/(?P<recipe_id>\d+)/$','edit'),
-    (r'^save/(?P<recipe_id>\d+)/$','save'),
 )

phlombay/recipes/views.py

 @login_required
 def new(request):
     """Create a new recipe."""
-    recipe = Recipe(name="Your Recipe Name", directions="Your recipe directions.", owner=request.user)
-    recipe.save()
-    return HttpResponseRedirect(reverse('phlombay.recipes.views.edit', args=[recipe.id]))
+    if request.method == 'GET':
+        recipe_form = RecipeForm()
+    elif request.method == 'POST':
+        post_data = _process_json_in_recipe_post_data(request.POST)
+        recipe_form = RecipeForm(data=post_data)
+
+        if recipe_form.is_valid():
+            recipe = recipe_form.save(commit=False)
+            recipe.creator = request.user
+            recipe.save()
+            return HttpResponseRedirect(reverse('phlombay.recipes.views.detail', args=[recipe.id]))
+
+    context = {'recipe_form': recipe_form, 'nav_section': 'new_recipe'}
+    return render(request, 'recipes/edit_recipe.html', context)
 
 
 @login_required
     if request.method == 'GET':
         recipe_form = RecipeForm(instance=recipe)
     elif request.method == 'POST':
-        post_data = request.POST.copy()
-        ingredients = {}
-        steps = {}
-        for k, v in post_data.items():
-            if k.startswith('ingredient-'):
-                field, number = tuple(k.split('-')[1:])
-                if number not in ingredients:
-                    ingredients[number] = {}
-                ingredients[number][field] = v
-            elif k.startswith('step-'):
-                field, number = tuple(k.split('-')[1:])
-                if number not in steps:
-                    steps[number] = {}
-                steps[number][field] = v
-        sorted_ingredients = [x[1] for x in sorted(ingredients.items(), key=lambda x: x[0])]
-        sorted_steps = [x[1] for x in sorted(steps.items(), key=lambda x: x[0])]
-        post_data['ingredients_json_blob'] = json.dumps(sorted_ingredients)
-        post_data['steps_json_blob'] = json.dumps(sorted_steps)
+        post_data = _process_json_in_recipe_post_data(request.POST)
         recipe_form = RecipeForm(instance=recipe, data=post_data)
 
         if recipe_form.is_valid():
     return render(request, 'recipes/edit_recipe.html', context)
 
 
-def save(request, recipe_id):
-    """Save a recipe.
-    Save and redirect to detail after a recipe is edited."""
-    recipe = get_object_or_404(Recipe, id=recipe_id)
-    if request.method == 'POST':
-        recipe.name = request.POST['name']
-        
-        if(request.POST.has_key('is_masterchef')):
-            if(request.POST.has_key('featured')):
-                recipe.featured = True
-            else:
-                recipe.featured = False
-         
-            
-        recipe.directions = request.POST['directions']
-        ingredients = [ingredient for ingredient in request.POST.keys() if ingredient.startswith("ingredient")]
-        for ingredient in recipe.ingredient_set.all(): #this is really bad and needs to be fixed
-            ingredient.delete()
-        for ingredient in ingredients:
-            val = ingredient[10:] #get the number of the ingredient, ingredient is a string, and we get everything after character 10 
-            ingredient_name = request.POST[ingredient]
-            ingredient_quantity = request.POST["quantity%s" % val]
-            if len(ingredient_name) > 0 and len(ingredient_quantity) > 0: #don't write empty fields to database
-                recipe.ingredient_set.create(name=ingredient_name, quantity=ingredient_quantity)
-        recipe.save()
-                 
-    return HttpResponseRedirect(reverse('phlombay.recipes.views.detail', args=[recipe_id]))
-
-
+def _process_json_in_recipe_post_data(post_data):
+    post_data = post_data.copy()
+    ingredients = {}
+    steps = {}
+    for k, v in post_data.items():
+        if k.startswith('ingredient-'):
+            field, number = tuple(k.split('-')[1:])
+            if number not in ingredients:
+                ingredients[number] = {}
+            ingredients[number][field] = v
+        elif k.startswith('step-'):
+            field, number = tuple(k.split('-')[1:])
+            if number not in steps:
+                steps[number] = {}
+            steps[number][field] = v
+    sorted_ingredients = [x[1] for x in sorted(ingredients.items(), key=lambda x: x[0])]
+    sorted_steps = [x[1] for x in sorted(steps.items(), key=lambda x: x[0])]
+    post_data['ingredients_json_blob'] = json.dumps(sorted_ingredients)
+    post_data['steps_json_blob'] = json.dumps(sorted_steps)
+    return post_data

phlombay/recipes/widgets.py

 
 class IngredientsWidget(Widget):
     def render(self, name, value, attrs=None):
-        ingredient_list = json.loads(value)
+        if value is not None and len(value.strip()):
+            ingredient_list = json.loads(value)
+        else:
+            ingredient_list = []
         widget_html = []
         counter = 0
         
                 continue
 
             ingredient_row_html = u"""
-            <tr>
+            <tr data-rownumber="{iteration}">
                 <td><input type="text" name="ingredient-quantity-{iteration}" value="{quantity}"/></td>
                 <td><input type="text" name="ingredient-unit-{iteration}" value="{unit}"/></td>
                 <td><input type="text" name="ingredient-ingredient-{iteration}" value="{ingredient}"/></td>
         
         # Add a blank row
         ingredient_row_html = u"""                   
-            <tr>
+            <tr data-rownumber="{iteration}">
                 <td><input type="text" name="ingredient-quantity-{iteration}" value=""/></td>
                 <td><input type="text" name="ingredient-unit-{iteration}" value=""/></td>
                 <td><input type="text" name="ingredient-ingredient-{iteration}" value=""/></td>
 
 class StepsWidget(Widget):
     def render(self, name, value, attrs=None):
-        steps_list = json.loads(value)
+        if value is not None and len(value.strip()):
+            steps_list = json.loads(value)
+        else:
+            steps_list = []
         widget_html = []
         counter = 0
         
         for step_json in steps_list:
             if len(step_json['text'].strip()):
                 step_row_html = u"""
-                <li><textarea name="step-text-{iteration}" class="span10" rows="4">{text}</textarea></li>
+                <li data-rownumber="{iteration}"><textarea name="step-text-{iteration}" class="span10" rows="4">{text}</textarea></li>
                 """.format(text=escape(step_json['text']),
                            iteration=counter)
                 widget_html.append(step_row_html)
 
         # Add a blank row
         step_row_html = u"""                   
-            <li><textarea name="step-text-{iteration}" class="span10" rows="4"></textarea></li>
+            <li data-rownumber="{iteration}"><textarea name="step-text-{iteration}" class="span10" rows="4"></textarea></li>
         """.format(iteration=counter)
         widget_html.append(step_row_html)
 

phlombay/templates/base.html

 					    <li{% if nav_section == 'index' %} class="active"{% endif %}><a href="{% url recipes.views.index %}">Home</a></li>
 					    <li{% if nav_section == 'browse_recipes' %} class="active"{% endif %}><a href="{% url recipes.views.browse_recipes %}">Browse Recipes</a></li>
 					    {% if request.user.is_authenticated %}
+					    	<li{% if nav_section == 'new_recipe' %} class="active"{% endif %}><a href="{% url recipes.views.new %}">New Recipe</a></li>
 					    	<li{% if nav_section == 'my_page' %} class="active"{% endif %}><a href="{% url recipes.views.my_page %}">My Page</a></li>
 					    	<li><a href="{% url recipes.views.phlombay_logout %}">Logout</a></li>
 					    {% else %}

phlombay/templates/recipes/detail.html

 		<div class="span10">
 			<h1>{{ recipe.name }}</h1>
 			<dl class="dl-horizontal">
+				<dt>Creator</dt>
+				<dd>{{ recipe.creator.username }}</dd>
 				<dt>Time Required</dt>
 				<dd>{{ recipe.time_required }}</dd>
 				<dt>Servings</dt>

phlombay/templates/recipes/edit_recipe.html

 {% block title %}Edit {{ recipe.name }} | phlombay.com{% endblock %}
 
 {% block content %}
+	{% if recipe %}
 	<h2>Edit {{ recipe.name }}</h2>
+	{% else %}
+	<h2>New Recipe</h2>
+	{% endif %}
 	
 	<form method="post">
 		<div class="row">
 <script type="text/javascript">
 $(function() {
 	$('#addIngredient').on('click', function() {
-		$('table#ingredientsTable tr:last input:first').each(function() {
-			var oldIndex = parseInt($(this).attr('name').split('-')[2]);
-			var oldIndexRegex = RegExp('-' + oldIndex, 'g');
-			var newIndex = oldIndex + 1;
-			$('table#ingredientsTable').append('<tr>' + $('table#ingredientsTable tr:last').html().replace(oldIndexRegex, '-' + newIndex.toString()) + '</tr>');
-		});
+		var oldIndex = parseInt($('table#ingredientsTable tr:last').attr('data-rownumber'));
+		var oldIndexRegex = RegExp('-' + oldIndex, 'g');
+		var newIndex = oldIndex + 1;
+		$('table#ingredientsTable').append('<tr data-rownumber="' + newIndex.toString()  + '">' + $('table#ingredientsTable tr:last').html().replace(oldIndexRegex, '-' + newIndex.toString()) + '</tr>');
 	});
 	
 	$('#addStep').on('click', function() {
-		$('ol#stepsList li:last textarea').each(function() {
-			var oldIndex = parseInt($(this).attr('name').split('-')[2]);
-			var oldIndexRegex = RegExp('-' + oldIndex, 'g');
-			var newIndex = oldIndex + 1;
-			$('ol#stepsList').append('<li>' + $('ol#stepsList li:last').html().replace(oldIndexRegex, '-' + newIndex.toString()) + '</li>');
-		});
+		var oldIndex = parseInt($('ol#stepsList li:last').attr('data-rownumber'));
+		var oldIndexRegex = RegExp('-' + oldIndex, 'g');
+		var newIndex = oldIndex + 1;
+		$('ol#stepsList').append('<li data-rownumber="' + newIndex.toString()  + '">' + $('ol#stepsList li:last').html().replace(oldIndexRegex, '-' + newIndex.toString()) + '</li>');
 	});
 });
 </script>

phlombay/templates/recipes/my_page.html

 		</tbody>
     </table>
     {% else %}
-    <p>You don't have any recipes! You should <a href="#">make one</a>.
+    <p>You don't have any recipes! You should <a href="{% url recipes.views.new %}">make one</a>.
     {% endif %}
 {% endblock %}
 
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.