diff --git a/cookbook/tests/test_views.py b/cookbook/tests/test_views.py index 664249f2..84bb0260 100644 --- a/cookbook/tests/test_views.py +++ b/cookbook/tests/test_views.py @@ -3,6 +3,8 @@ from django.contrib.auth.models import User from django.test import TestCase, Client from django.urls import reverse +from cookbook.models import Recipe, RecipeIngredients + class TestViews(TestCase): @@ -43,3 +45,28 @@ class TestViews(TestCase): r = self.anonymous_client.get(url) self.assertEqual(r.status_code, 302) + + def test_internal_recipe_update(self): + recipe = Recipe.objects.create( + name='Test', + created_by=auth.get_user(self.client) + ) + + url = reverse('edit_internal_recipe', args=[recipe.pk]) + + r = self.client.get(url) + self.assertEqual(r.status_code, 200) + + r = self.anonymous_client.get(url) + self.assertEqual(r.status_code, 302) + + r = self.client.post(url, {'name': 'Changed', 'working_time': 15, 'waiting_time': 15, 'ingredients': '[]'}) + self.assertEqual(r.status_code, 200) + + recipe = Recipe.objects.get(pk=recipe.pk) + self.assertEqual('Changed', recipe.name) + + r = self.client.post(url, + {'name': 'Changed', 'working_time': 15, 'waiting_time': 15, 'ingredients': '[{"name":"Tomato","unit__name":"g","amount":100,"delete":false},{"name":"Egg","unit__name":"Piece","amount":2,"delete":false}]'}) + self.assertEqual(r.status_code, 200) + self.assertEqual(2, RecipeIngredients.objects.filter(recipe=recipe).count()) diff --git a/cookbook/views/edit.py b/cookbook/views/edit.py index 602e9c42..97f9b47c 100644 --- a/cookbook/views/edit.py +++ b/cookbook/views/edit.py @@ -42,9 +42,12 @@ def convert_recipe(request, pk): @login_required def internal_recipe_update(request, pk): recipe_instance = get_object_or_404(Recipe, pk=pk) + status = 200 if request.method == "POST": form = InternalRecipeForm(request.POST, request.FILES) + form.instance = recipe_instance + if form.is_valid(): recipe = recipe_instance recipe.name = form.cleaned_data['name'] @@ -95,9 +98,9 @@ def internal_recipe_update(request, pk): recipe.keywords.set(form.cleaned_data['keywords']) messages.add_message(request, messages.SUCCESS, _('Recipe saved!')) - return HttpResponseRedirect(reverse('edit_internal_recipe', args=[pk])) else: - messages.add_message(request, messages.ERROR, _('There was an error importing this recipe!')) + messages.add_message(request, messages.ERROR, _('There was an error saving this recipe!')) + status = 403 else: form = InternalRecipeForm(instance=recipe_instance) @@ -105,7 +108,7 @@ def internal_recipe_update(request, pk): return render(request, 'forms/edit_internal_recipe.html', {'form': form, 'ingredients': json.dumps(list(ingredients)), - 'view_url': reverse('view_recipe', args=[pk])}) + 'view_url': reverse('view_recipe', args=[pk])}, status=status) class SyncUpdate(LoginRequiredMixin, UpdateView):