【发布时间】:2016-10-15 19:06:48
【问题描述】:
我正在学习 modelforms 帮助程序,据我了解,表单验证的最佳做法是在简单的代码之后将表单保存到 DB 模型对象,如下所示:
def my_view(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = MyForm(request.POST)
# check whether it's valid:
if form.is_valid():
form.save()
return redirect somewhere
else:
form = MyForm()
return render(request, 'mysite.html', {'form': form})
但是,我想向此模型对象添加表单中未明确显示的额外数据。例如,如果我想为在服务器端生成的对象添加日期戳怎么办?如何将更多信息保存到同一个模型对象中,这样做的最佳做法是什么?
【问题讨论】:
-
“更多数据”是什么意思?模型的更多字段?
-
使用
commit=False调用保存。 SO上有数百个例子。 -
更多数据是指更多字段。假设我的模型中有一个字段是创建的日期时间,但我想在服务器端生成该日期,而不是通过表单。之后如何将这些额外的字段添加到数据库中的模型对象中?
-
好的,我找到了 commit-false,谢谢 Daniel
标签: django