如何在django中更新现有记录而不是创建新记录?

时间:2016-02-15 15:27:55

标签: python django django-forms

所以我在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})

但是当我提交表单时,它实际上创建了一条新记录,而不是编辑旧记录。有任何建议如何更新旧记录而不是创建新记录?

2 个答案:

答案 0 :(得分:3)

您应该明白,您在is_valid块中专门调用create,因此您自然会创建一条记录。但是,通过这样做,您可以绕过模型形式为您提供的所有帮助。

您应该通过initial,而不是传递instance;然后在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})

答案 1 :(得分:0)

使用

Ti.App.addEventListener('resume', function(){
    Ti.API.log("resume event triggered");
});
Ti.App.addEventListener('pause', function(){
    Ti.API.log("paused event triggered");
});

您正在创建并保存新实例。

当您在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) 处获得旧配方时,要更新它,您只需要用以下内容替换这些行:

recipe