开发者

Django: using ModelForm to edit existing database entry

开发者 https://www.devze.com 2023-04-03 08:25 出处:网络
I have created a ModelForm class to be able 开发者_C百科to create and edit database entries. Creating new entries works well, however, i dont know how to use ModelForms to edit/update an existing entr

I have created a ModelForm class to be able 开发者_C百科to create and edit database entries. Creating new entries works well, however, i dont know how to use ModelForms to edit/update an existing entry. I can instantiate a ModelForm with a database instance using:

form  = MyModelForm(instance=MyModel.objects.get(pk=some_id))

However, when i pass this to a template and edit a field and then try to save it, i create a new database entry instead of updating "some_id"?

Edit1: This is my view

def editData(request):
if request.method == 'POST':
    form = MyModelForm(request.POST, request.FILES)

    if form.is_valid():
        editedEntry = form.save() # <-- creates new entry, instead of updating


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)


Also possible and slightly shorter:

instance = MyModel.objects.get(whatever)
form = MyModelForm(request.POST or None, instance=instance)
...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号