Variable number of inputs with Django forms possible?

前端 未结 3 1163
無奈伤痛
無奈伤痛 2020-12-24 08:58

Is it possible to have a variable number of fields using django forms?

The specific application is this:

A user can upload as many pictures as they want on t

相关标签:
3条回答
  • 2020-12-24 09:22

    Yes, it's possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields.

    class EligibilityForm(forms.Form):
        def __init__(self, *args, **kwargs):
            super(EligibilityForm, self).__init__(*args, **kwargs)
            # dynamic fields here ...
            self.fields['plan_id'] = CharField()
        # normal fields here ...
        date_requested = DateField()
    

    For a better elaboration of this technique, see James Bennett's article: So you want a dynamic form?

    http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/

    0 讨论(0)
  • 2020-12-24 09:36

    Use either multiple forms (django.forms.Form not the tag)

    class Foo(forms.Form):
        field = forms.Charfield()
    
    forms = [Foo(prefix=i) for i in xrange(x)]
    

    or add multiple fields to the form dynamically using self.fields.

    class Bar(forms.Form):
        def __init__(self, fields, *args, **kwargs):
            super(Bar, self).__init__(*args, **kwargs)
            for i in xrange(fields):
                self.fields['my_field_%i' % i] = forms.Charfield()
    
    0 讨论(0)
  • 2020-12-24 09:47

    If you run

    python manage.py shell
    

    and type:

    from app.forms import PictureForm
    p = PictureForm()
    p.fields
    type(p.fields)
    

    you'll see that p.fields is a SortedDict. you just have to insert a new field. Something like

    p.fields.insert(len(p.fields)-2, 'fieldname', Field())
    

    In this case it would insert before the last field, a new field. You should now adapt to your code.

    Other alternative is to make a for/while loop in your template and do the form in HTML, but django forms rock for some reason, right?

    0 讨论(0)
提交回复
热议问题