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

查看:86
本文介绍了如何从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.

第一个问题:在隐藏的字段中是否有正确的方法?

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 direct_to_template(request, 'my_template.html', {'form': form}     

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

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