Django视图中的多种不同形式

问题描述 投票:0回答:1

我想知道是否有一种方法可以在一个视图中包含多个不同的表单,并按下一个提交按钮来存储信息。 我有以下表单,第一个是我应该首先创建的通用表单:

class GeneralForm(forms.ModelForm):
    name = forms.CharField(max_length=50)

    TYPE_CHOICES = (
        ("C","C"),
        ("E","E")
    )

    STATUS_CHOICES = (
        ("A", "A"),
        ("F", "F"),
    )
    type=forms.ChoiceField(choices=STATUS_CHOICES)
    number=forms.CharField(max_length=50)
    TURN_CHOICES = (
        ("1", "1"),
        ("2", "2"),
        ("3", "3")
    )
    turn = forms.ChoiceField(choices=TURN_CHOICES)

   

    class Meta:
        model = models.General
        fields=["name","type","number","turn"]

第二个需要第一个的实例,第三个也需要:

class TypeOneForm(forms.ModelForm):
    num_chairs=forms.IntegerField()
    num_instalations = forms.IntegerField()
    total = forms.IntegerField()
    num_programs = forms.IntegerField()


    class Meta:
        model = models.TypeOne
        fields=["num_chairs","num_instalations","total","billetes_cien"]



class TypeTwoForm(forms.ModelForm):
    
    num_available_seats=forms.IntegerField()
    num_available_instalations = forms.IntegerField()
    total = forms.IntegerField()
    num_new_programs = forms.IntegerField()


    class Meta:
        model = models.TypeTwo
        fields=["num_available_seats", "num_available_instalations","total","num_programs" ]

我正在阅读我可以使用 FormSets,但我不确定是否可以使用不同的表单而不是同一表单的多个实例

django django-views django-forms django-templates
1个回答
0
投票

您可以使用

get_context_data()
并将表单放入上下文中,但是如果您想填写表单的某些字段,则需要验证表单。

def get_context_data(self, **kwargs):
    context = super().get_context_data()
    context['general_form'] = GeneralForm()
    return context

这样验证

def post(self, request, *args, **kwargs):
    form = GeneralForm(request.POST)
    if form.is_valid():
        form.instance.author = request.user
        form.save()
        return redirect(reverse('general_form'))
© www.soinside.com 2019 - 2024. All rights reserved.