我正在使用 django-formtools 创建表单向导。我想使用 get-parameter 预先填写表单的第一部分。首先,我使用常规 django 表单验证 GET 数据。
表格.py
class MiniConfiguratorForm(forms.Form):
width = forms.IntegerField(min_value=MIN_WIDTH, max_value=MAX_WIDTH, initial=25, label=_('width'))
height = forms.IntegerField(min_value=MIN_HEIGHT, max_value=MAX_HEIGHT, initial=25, label=_('height'))
amount = forms.IntegerField(min_value=MIN_QUANTITY, max_value=MAX_QUANTITY, initial=1, label=_('amount'))
class ConfiguratorStep1(forms.Form):
# ...
width = forms.IntegerField(widget=forms.NumberInput(), min_value=MIN_WIDTH, max_value=MAX_WIDTH, initial=25, label=_('width'))
height = forms.IntegerField(widget=forms.NumberInput(), min_value=MIN_HEIGHT, max_value=MAX_HEIGHT, initial=25, label=_('height'))
amount = forms.IntegerField(widget=forms.NumberInput(), min_value=MIN_QUANTITY, max_value=MAX_QUANTITY, initial=1, label=_('amount'))
class ConfiguratorStep2(forms.Form):
name = forms.CharField(max_length=100, required=True)
phone = forms.CharField(max_length=100)
email = forms.EmailField(required=True)
视图.py
class ConfiguratorWizardView(SessionWizardView):
template_name = "www/configurator/configurator.html"
form_list = [ConfiguratorStep1, ConfiguratorStep2]
def done(self, form_list, **kwargs):
return render(self.request, 'www/configurator/done.html', {
'form_data': [form.cleaned_data for form in form_list]
})
def get(self, request, *args, **kwargs):
"""
This method handles GET requests.
If a GET request reaches this point, the wizard assumes that the user
just starts at the first step or wants to restart the process.
The data of the wizard will be reset before rendering the first step
"""
self.storage.reset()
# reset the current step to the first step.
self.storage.current_step = self.steps.first
mini_configurator = MiniConfiguratorForm(data=request.GET)
init_data = None
if mini_configurator.is_valid():
init_data = {
'width': '35',
'height': '33',
'amount': '17',
}
print("valid")
else:
print("invalid haxx0r")
return self.render(self.get_form(data=init_data))
我的方法是覆盖 get() 并在 self.get_form(data) 中传递数据。这不能正常工作。所有字段均为空。如果我在没有参数的情况下访问表单,则表单会正确呈现。