我想实现这个场景:我希望有一个简单的表单,包含一些文本字段和多个提交按钮。单击按钮时,应执行此按钮的操作,并应更新相应的表单域。我们说,我们有一个加密演示。当我按加密时,明文被加密读写并写入密文字段,依此类推。
我有一个非常简单的形式:
from django import forms
class ABEForm(forms.Form):
master_private_key = forms.CharField(required=False,label="Master Secret Key",widget=forms.Textarea(attrs={'width':"100%", 'cols' : "80", 'rows': "20", }))
master_public_key = forms.CharField(required=False,label="Master Public Key",widget=forms.Textarea(attrs={'width':"100%", 'cols' : "80", 'rows': "20", }))
还有一个非常简单的观点:
def form_submit(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:
#check what submit button was pressed
if 'abe_setup' in request.POST:
form = ABEForm(request.POST)
abesetupdata = ABE_Scheme_SetupData()
abesetupdata.init_setup()
form.master_private_key = abesetupdata.master_key
form.master_public_key = abesetupdata.master_public_key
print("privkey =>", form.master_private_key)
print("pubkey =>", form.master_public_key)
return render(request, 'webfrontend/abeform.html', {'form': form})
elif 'abe_keyen' in request.POST:
return render(request, 'webfrontend/abeform.html', {'form': form})
# if a GET (or any other method) we'll create a blank form
else:
form = ABEForm()
return render(request, 'webfrontend/abeform.html', {'form': form})
案件处理(按下了哪个按钮)似乎没问题。但是,每当我按下设置按钮并重新渲染表单时,表单都是空的。我错过了什么?我知道你可以提供一个字典来将数据绑定到表单。但是使用request.POST
作为数据源应该可以正常工作吗?
print语句可以工作并将表单内容打印到命令行...
答案 0 :(得分:0)
我认为当无法分配未绑定和字段数据时,表单是不可变的。我必须创建一个新表单,在那里传递一个字典:
data = {'master_private_key': abesetupdata.master_private_key,
'master_public_key': abesetupdata.master_public_key,
'attribute_key' : abesetupdata.attribute_key,
}
form = ABEForm(data)