Django: using ModelForm to edit existing database entry

后端 未结 2 974
日久生厌
日久生厌 2020-12-05 04:42

I have created a ModelForm class to be able to create and edit database entries. Creating new entries works well, however, i dont know how to use ModelForms to edit/update a

相关标签:
2条回答
  • 2020-12-05 05:02

    Remember you still need to use the instance parameter when you instantiate on POST.

    instance = MyModel.objects.get(whatever)
    if request.method == "POST":
        form = MyModelForm(request.POST, instance=instance)
        ...
    
    else:
        form = MyModelForm(instance=instance)
    
    0 讨论(0)
  • 2020-12-05 05:10

    Also possible and slightly shorter:

    instance = MyModel.objects.get(whatever)
    form = MyModelForm(request.POST or None, instance=instance)
    ...
    
    0 讨论(0)
提交回复
热议问题