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

标签 python django templates django-forms django-formwizard

我正在使用 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/

相关文章:

python - 如何根据Python组合字符串找到正确的网站链接

python - opencv 2.4.9 中 findcontour 函数返回的值是什么

python - Django URL 正则表达式出现类型错误

c++ - 对不完整类型的 std::vector 的引用或指针

c++ - 当函数不存在时 SFINAE 回退

python - 在Python中使用MXNet预训练图像分类模型

python - 无法返回列表中的第一个偶数

python - 浏览器未读取我的网址

python - 帮助! Django 媒体小部件没有出现

c++ - 用于模拟运行时数字模板参数的成语?