gpt4 book ai didi

python - Django formwizard - 无法从步骤1到步骤2获取数据

转载 作者:太空宇宙 更新时间:2023-11-03 17:38:18 25 4
gpt4 key购买 nike

我正在使用 Django 表单向导将数据输入表单页面,然后将其显示在确认页面中。但是,当我尝试调用 self.get_cleaned_data_for_step(step_name) 时,我得到一个“‘MyForm’对象没有属性‘cleaned_data’”。我知道如果表单无法验证,就会发生这种情况,因此我重写了表单类中的 is_valid 方法以始终返回 True,就像测试一样,但我仍然收到此错误。我的相关代码如下:

forms.py

...
class MealForm(forms.Form):

modifications = forms.CharField()

def __init__(self, *args, **kwargs):
menu_items = kwargs.pop('menu_items')
super(MealForm, self).__init__(*args, **kwargs)

for item in menu_items:
self.fields[str(item.name)] = forms.IntegerField(widget=forms.NumberInput(attrs={'value': 0}))

def is_valid(self):
return True

urls.py

...
url(r'^(?P<url>[-\w]+)/meal/$',
login_required(views.MealFormWizard.as_view(views.MealFormWizard.FORMS)), name="meal"),

views.py

...
class MealFormWizard(SessionWizardView):

FORMS = [('meal_form', MealForm),
('meal_form_confirmation', MealFormConfirmation)]

TEMPLATES = {'meal_form': 'restaurant/createMeal.html',
'meal_form_confirmation': 'restaurant/confirmation.html'}

def get_form_kwargs(self, step=None):
kwargs = {}

url = self.kwargs['url']
restaurant = Restaurant.objects.get(url=url)
menu_items = MenuItem.objects.filter(restaurant=restaurant)

if step == 'meal_form':
kwargs['menu_items'] = menu_items

return kwargs

def get_context_data(self, form, **kwargs):

context = super(MealFormWizard, self).get_context_data(form=form, **kwargs)

if self.steps.current == 'meal_form':
context.update({...objects/vars...})

if self.steps.current == 'meal_form_confirmation':
cd = self.get_cleaned_data_for_step('meal_form') **This is where my error occurs**

createMeal.html

...
<form action="" method="post">
{% csrf_token %}
{{ wizard.management_form }}

{{ wizard.form }}

<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.next }}">Submit Meal</button>
</form>

在createMeal.html中提交表单后,我应该能够通过调用self.get_cleaned_data_for_step('meal_form')来访问views.py中MealFormWizard类的get_context_data方法中上一步的清理数据。然而事实并非如此,但我不知道我错在哪里。

最佳答案

覆盖is_valid这样是行不通的 - 如果您按照代码操作,您将看到表单的 cleaned_data属性由正常 is_valid 设置方法。

文档说,如果表单无效,则 get_cleaned_data_for_step将返回None ,您需要编写代码以便它可以处理这个问题。

关于python - Django formwizard - 无法从步骤1到步骤2获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30903300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com