如何从表单中获取所有数据并保存在Django的数据库中?

时间:2013-08-02 07:24:36

标签: django forms django-forms

我在模板中调用表单:

{{ form.as_p }}

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

info = form.POST 

并保存在视频表中,如下所示:

video = info.save()

Django有可能吗?我可以逐个获取每个字段并将其保存在数据库中。但我想快速做到这一点。

1 个答案:

答案 0 :(得分: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
相关问题