Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable number of inputs with Django forms possible?

Tags:

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 the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload.

So how do I get django to generate a form using a variable number of input fields (which could be passed as an argument if necessary)?

edit: a few things have changed since the article mentioned in jeff bauer's answer was written.

Namely this line of code which doesn't seem to work:

# BAD CODE DO NOT USE!!!
return type('ContactForm', [forms.BaseForm], { 'base_fields': fields })

So here is what I came up with...

The Answer I used:


from tagging.forms import TagField
from django import forms

def make_tagPhotos_form(photoIdList):
    "Expects a LIST of photo objects (ie. photo_sharing.models.photo)"

    fields = {}

    for id in photoIdList:
        id = str(id)

        fields[id+'_name'] = forms.CharField()
        fields[id+'_tags'] = TagField()
        fields[id+'_description'] = forms.CharField(widget=forms.Textarea)

    return type('tagPhotos', (forms.BaseForm,), { 'base_fields': fields })

note tagging is not part of django, but it is free and very useful. check it out: django-tagging

like image 695
Jiaaro Avatar asked Jan 04 '09 22:01

Jiaaro


People also ask

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is the difference between models and forms in Django?

The main difference between the two is that in forms that are created from forms. ModelForm , we have to declare which model will be used to create our form. In our Article Form above we have this line " model = models. Article " which basically means we are going to use Article model to create our form.


1 Answers

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/

like image 135
Jeff Bauer Avatar answered Sep 19 '22 15:09

Jeff Bauer