如何从 Django 中的编辑表单更新对象? [英] How to update an object from edit form in Django?

查看:30
本文介绍了如何从 Django 中的编辑表单更新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是新手问题,请耐心等待.

Possibly a newbie question, so please bear with me.

我有一个 Django 表单,用于编辑模型的某个实例.为了知道正在编辑哪个对象,我有一个包含对象 id 的隐藏字段,以及包含 id 的 URL.

I have a Django form that edits a certain instance of a Model. In order to know which object is being edited, I have a hidden field containing the id of the object, along with the URL containing the id.

第一个问题:将对象的 id 放在隐藏字段中是正确的做法吗?

First question: Is having the id of the object in a hidden field the right way of doing it?

我(可能毫无根据)担心仅将其作为 url 的一部分是有人可以打开一个对象 ID 的页面,将表单提交给另一个,然后该对象将被覆盖.这就是我尝试使用隐藏字段的原因.

My (possibly unfounded) concern with having it only as part of the url is that someone could then open the page of one object id, submit the form to another, and that object will then be overwritten. That's why I'm trying to use a hidden field.

将 id 存储在隐藏字段中的问题在于,在验证表单时,Django 抱怨该对象没有唯一的 id(显然).

The problem with storing the id in a hidden field is that, on validation of the form, Django complains that the object does not have an unique id (obviously).

第二个问题:如果一个唯一字段是表单的一部分,如何告诉 Django 忽略该键已经存在的事实,以便更新对象?

Second question: If a unique field is part of a form, how does one tell Django to ignore the fact that that key already exists, in order to update the object?

推荐答案

为什么不直接使用 ModelForm?

Why don't you just use ModelForm?

# forms.py
# ...
class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

# views.py
# ...    
def my_view(request, id): 
    instance = get_object_or_404(MyModel, id=id)
    form = MyForm(request.POST or None, instance=instance)
    if form.is_valid():
        form.save()
        return redirect('next_view')
    return render(request, 'my_template.html', {'form': form}) 

参见 https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method 了解更多详情.

See https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/#the-save-method for more details.

这篇关于如何从 Django 中的编辑表单更新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆