0

我将模板中的表单称为:

{{ form.as_p }}

现在,当用户提交表单时,我想立即获取数据。像这样的东西:

info = form.POST 

并像这样保存在视频表中:

video = info.save()

这在 Django 中可能吗?我可以一一获取每个字段并将其保存在数据库中。但我想以这种快速的方式进行。

4

1 回答 1

1

假设您有一个 Django 模型表单类(您不能直接在 DB 中保存一个简单的表单,因为没有相应的模式,但您可以使用模型表单)

class MyForm(forms.ModelForm):
  field1 = forms.IntegerField(...)
  ...

你在模板中渲染它{{ form.as_p }}

然后在接收视图中,执行以下操作:

def myview(request):
  if request.method == "POST":
    form = MyForm(request.POST)
    if form.is_valid():
      form.save() # here you save the form all at once
    else:
      ... # here return the "form" to the template, and render it with form.as_p: it will display the validation errors
  else:
    ... # here treat the get request. If not get: return an Http 404 response
于 2013-08-02T07:37:26.630 回答