Reputation:
So I have the following function in views.py:
def recipe_edit(request, pk):
recipe = get_object_or_404(Recipe, pk=pk)
if request.method == "POST":
initial = {'title': recipe.title, 'description': recipe.description}
form = RecipeForm(request.POST, initial=initial)
if form.is_valid():
current_user = request.user
data = form.cleaned_data
recipe_data=Recipe.objects.create(user=current_user, title=data['title'], description=data['description'])
recipe_data.save( force_insert=False, force_update=False, using=None)
return HttpResponseRedirect('recipe_detail', pk=recipe.pk)
else:
initial = {'title': recipe.title, 'description': recipe.description}
form = RecipeForm(initial=initial)
return render(request, 'recipe_edit.html', {'form': form, 'recipe':recipe})
But when I submit the form, instead of editing the old record, it actually creates a new record. Any suggestions how do I update the old record instead of creating a new one?
Upvotes: 2
Views: 1896
Reputation: 600041
It should be obvious to you that you are specifically calling create
in the is_valid block, so naturally you will create a record. As well as always creating, though, by doing this you are bypassing all the help that a modelform gives you.
Instead of passing initial
, you should be passing instance
; and then in the is_valid block you should be calling form.save
.
def recipe_edit(request, pk):
recipe = get_object_or_404(Recipe, pk=pk)
if request.method == "POST":
form = RecipeForm(request.POST, instance=recipe)
if form.is_valid():
recipe = form.save(commit=False)
recipe.user = request.user
recipe.save()
return redirect('recipe_detail', pk=recipe.pk)
else:
form = RecipeForm(instance=recipe)
return render(request, 'recipe_edit.html', {'form': form, 'recipe':recipe})
Upvotes: 3
Reputation: 3144
With the lines
recipe_data=Recipe.objects.create(user=current_user, title=data['title'], description=data['description'])
recipe_data.save( force_insert=False, force_update=False, using=None)
you are creating and saving a new instance.
As you have your old recipe at recipe
, to update it you just need to replace those lines with something like this:
recipe.title = data['title']
recipe.description = data['description']
recipe.save()
Upvotes: 0