首页 > 解决方案 > 使用基于 Django 类的 CreateView 执行多步骤表单

问题描述

我有多个基于类的创建视图。我的目标是链接所有 createview,这样当我发布第一个 createview 时,它会将我重定向到第二个 createview,在那里它将检索从第一个 createview 输入的数据。

有谁知道这个问题的解决方案?

第一个 createview (Step01) 包含与代码类似的 django-inline-formset-factory 代码,而其余 (Step02 和 Step03) 包含基本代码。

我已经提到了这个链接,但解决方案是基于使用基于函数的视图。也尝试过使用 Django 的 Form-Wizard,但是用它处理 django-inline-formset 对我来说仍然太复杂了。

我为什么要这样做?这样每个组级别(即一般、员工、管理人员)都可以访问他们各自的视图,但不能访问其他组级别的视图。

这是我当前的代码:

模型.py

class Model_Step01_Cart(models.Model):
    cart_name = models.CharField(max_length=100)

class Model_Step01_CartItem(models.Model):
    cart = models.ForeignKey(Profile)
    item_name = models.CharField(max_length = 100)
    item_quantity = models.FloatField(null = True, blank = True)

class Model_Step02_Staffnote(models.Model):
    note_staff = models.TextField(max_length = 500, null = True, blank = True)

class Model_Step03_Managernote(models.Model):
    note_manager = models.TextField(max_length = 500, null = True, blank = True)

表格.py

class Form_Step01_Cart(forms.ModelForm):
    class Meta:
        model = Model_Step01_Cart
    fields = ["cart_name"]

class Form_Step01_CartItem(forms.ModelForm):
    class Meta:
        model = Model_Step01_CartItem
    fields = ["cart", "item_name", "item_quantity"]

Formset_CartItem = forms.inlineformset_factory(
    Model_Step01_Cart,
    Model_Step01_CartItem,
    form = Form_Step01_CartItem,
    extra = 3
    )

class Form_Step02(forms.ModelForm):
    class Meta:
        model = Model_Step02_Staffnote
    fields = ["note_staff"]

class Form_Step03(forms.ModelForm):
    class Meta:
        model = Model_Step03_Managernote
    fields = ["note_manager"]

视图.py

class View_Step01(CreateView):
    # contains formset_factory for "Model_Step01_Cart" and "Model_Step01_CartItem"
    model = Model_Step01_Cart
    fields = ["cart_name"]

    # similar with the code displays here: https://medium.com/@adandan01/django-inline-formsets-example-mybook-420cc4b6225d

class View_Step02(CreateView):
    # gets info from step 01, and adds staff's note

class View_Step03(CreateView):
    # gets info from step 01 and 02, and adds manager's note.

标签: django

解决方案


找到我在多个视图中拆分单个表单的答案。您可以配置gist 脚本以满足您的要求

对于基于类的视图,将一个视图的成功 url 映射到另一个视图CreateView.as_view(model=myModel, success_url="/<path-to-view2/")


推荐阅读