简体   繁体   中英

How to update an existing record instead of creating a new one in django?

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?

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})

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM