django动态表单生成

时间:2012-11-21 00:37:20

标签: django django-forms

说我有一个这样的模型:

 class ComponentLength(models.Model):
    component_name = models.CharField(max_length=155)
    length1 = models.IntegerField()
    length2 = models.IntegerField()
    length3 = models.IntegerField()
    length4 = models.IntegerField()

现在我有一个表单供用户选择一个组件,在下一页我想显示4个不同长度选项的复选框,这些选项对于不同的组件是不同的。

Django根据用户已选择的组件名称(在会话数据中可访问)生成具有这些复选框的表单的最佳方式是什么。

任何帮助都非常感激。

2 个答案:

答案 0 :(得分:0)

您可以使用普通的django表单并在实例化时在 init 方法中更改其字段。像这样:

class SecondForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(SecondForm, self).__init__(*args, **kwargs)
        try:
            #get the object, something like this:
            obj_ = ComponentLength.objects.get(component_name = session.get('component_name_or_whatever_you_stored'))
        except:
            #handle the error case, e.g:
            return

            self.fields['length1'] = forms.CheckboxInput(attrs={'value' : obj_.length1 })
            self.fields['length2'] = forms.CheckboxInput(attrs={'value' : obj_.length2 })
            self.fields['length3'] = forms.CheckboxInput(attrs={'value' : obj_.length3 })
            self.fields['length4'] = forms.CheckboxInput(attrs={'value' : obj_.length4 })
            #Consider using a hidden input instead of polluting the session variables
            #with form data
            self.fields['component_length'] = forms.HiddenInput(attrs={'value' : obj_.pk})

以上代码未经过测试,但我希望它能够正常运行。请告诉我它是怎么回事。

答案 1 :(得分:0)

表格向导正是您所需要的。

https://docs.djangoproject.com/en/1.7/ref/contrib/formtools/form-wizard/

请参阅此处显示的示例https://docs.djangoproject.com/en/1.7/ref/contrib/formtools/form-wizard/#usage-of-namedurlwizardview

此处如何定义表单https://docs.djangoproject.com/en/1.7/ref/contrib/formtools/form-wizard/#conditionally-view-skip-specific-steps

我没有测试下面的代码,但它应该类似于以下内容:

的myapp / forms.py

from django.forms import ModelForm

from myapp.models import ComponentLength

class ComponentLengthNameForm(ModelForm):

    class Meta:
        model = ComponentLength
        fields = ['component_name',]

class ComponentLengthChoicesForm(ModelForm):

    class Meta:
        model = ComponentLength
        fields = ['length1', 'length2', 'length3', 'length4',]

的myapp / views.py

from django.contrib.formtools.wizard.views import SessionWizardView
from django.shortcuts import render_to_response

class ComponentWizard(SessionWizardView):

    def done(self, form_list, **kwargs):
        return render_to_response('done.html', {
            'form_data': [form.cleaned_data for form in form_list],
        })

的myapp / urls.py

from django.conf.urls import url, patterns

from myapp.forms import ComponentLengthNameForm, ComponentLengthChoicesForm
from myapp.views import ContactWizard

named_contact_forms = (
    ('name', ComponentLengthNameForm),
    ('length-choices', ComponentLengthChoicesForm),
)

component_wizard = ComponentWizard.as_view(named_contact_forms,
    url_name='component-wizard-form-step', done_step_name='finished')

urlpatterns = patterns('',
    url(r'^my-form/(?P<step>.+)/$', component_wizard, name='component-wizard-form-step'),
    url(r'^my-form/$', component_wizard, name='component-wizard-form'),
)