[英]How to update an existing record instead of creating a new one in django?
So I have the following function in views.py: 所以我在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? 有什么建议我如何更新旧记录而不是创建新记录?
It should be obvious to you that you are specifically calling create
in the is_valid block, so naturally you will create a record. 您应该明白,您在is_valid块中专门调用create
,因此您自然会创建一条记录。 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
; 你应该传递instance
,而不是传递initial
; and then in the is_valid block you should be calling form.save
. 然后在is_valid块中,您应该调用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})
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
有旧配方时,要更新它,您只需要用以下内容替换这些行:
recipe.title = data['title']
recipe.description = data['description']
recipe.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.