【问题标题】:How to use form.cleaned_data django如何使用 form.cleaned_data django
【发布时间】:2018-06-21 10:30:28
【问题描述】:

在form.is_valid()之后,我们得到form.cleaned_data。如何在下一页使用这些清理后的数据。

例如,处理完表单页面后,我们将客户重定向到下一页,我想在此处使用已清理数据的信息,例如姓名、联系方式、地址等字段,以显示在下一页中。

def ind(request):
    if request.method == 'POST':
        form = form_name(request.POST)
        if form.is_valid():
            print(form.cleaned_data)
            return render(request, 'app_one/abc.html', {'data': form.cleaned_data})
            # form.save(commit=True)
            # return render(request,'app_one/index.html')
    else:
        form=form_name()
    return render(request,'app_one/index.html',{'form':form)

【问题讨论】:

  • 你能用一些例子或用例来详细说明你的问题吗?
  • 当然,就像客户在首页进行购买,我们在下一页生成收据。因此,在第一页填写的客户详细信息需要在第二页显示这些详细信息作为收据。

标签: django django-models django-forms


【解决方案1】:

调用form.is_valid() 方法后,我们将得到一个经过验证的数据。一旦我们拥有经过验证的数据,我们就可以随意使用。 适合你的情况

在第一页填写的客户详细信息需要在第二页显示这些详细信息作为收据。

您可以创建一个名为Reciept 的模型并将详细信息保存在模型中以供将来参考。如果您希望在其他页面视图中显示这些详细信息,则只需将模型对象传递给 context 即可呈现详细信息。

您可以使用如下清理后的数据

def ind(request):
    if request.method == 'POST':
        form = form_name(request.POST)
        if form.is_valid():
            context = {}.update(form.cleaned_data)
            return render(request, 'app_one/abc.html', context)
            # form.save(commit=True)
            # return render(request,'app_one/index.html')
    else:
        form=form_name()
    return render(request,'app_one/index.html',{'form':form)

示例表格:

class MyForm(forms.Form):
     reciept_num = forms.CharField()

以上面的形式为例 您可以使用名称reciept_num 访问模板中的reciept_num 数据。

【讨论】:

  • 有什么办法可以将cleaned_form作为字典发送到下一页并使用它。
【解决方案2】:

您可以像往常一样将 clean_data 分配给表单的变量 例如your_data=form.cleaned_data['your_data']

之后,将这些变量传递给上下文。 例如上下文 = { “你的数据”:你的数据
}

最后返回模板。 例如return(request,'template.html',context=context)

在“template.html”中,使用变量作为 {{your_data}}。

【讨论】:

    猜你喜欢
    • 2013-04-03
    • 2010-09-23
    • 2018-12-07
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2010-10-12
    • 2015-07-04
    • 1970-01-01
    相关资源
    最近更新 更多