1

The problem I have is in my template, there is a form that can expand to an unknown number of inputs (file & text) for submitting images & titles. My Photo Model has 2 fields : ImageField & CharField. Based on the number of images uploaded, I want to create that number of photo objects in my view.

So a user might want to upload 2 photos or another will upload 10. I have read Jacobian's post on dynamic form generation, but that seems limited to a known number of fields.

How do you structure the form class for handling an unknown number of arguments?

So far I have:

class PhotoForm(forms.Form):        

def __init__(self, *args, **kwargs):
    super(PhotoForm, self).__init__(*args, **kwargs)
    print args
    self.fields['photo'] = forms.ImageField(
        label=_("Photo 1 (Required)"),
        widget=forms.FileInput( attrs={'class':''}),
            required=True)
    self.fields['photo_desc'] = forms.CharField(
        label=_("Photo 1 Description"),
        widget=forms.TextInput(),
        required=True)

I believe I need to loop over the arguments which will create N number of fields. That will then allow the form to validate when I call form.is_valid().

Is there something I am missing from this?

Community
  • 1
  • 1
bingo4344
  • 31
  • 1
  • 3
  • 1
    seems you need [formset](https://docs.djangoproject.com/en/1.4/topics/forms/formsets/) – okm May 15 '12 at 04:05
  • that looks promising ... will look into formsets now..thanks! – bingo4344 May 15 '12 at 04:08
  • It looks like formset is only for setting the amount upfront? What if you want the user to be able to expand that amount? – bingo4344 May 15 '12 at 04:31
  • possible duplicate of [Dynamically adding a form to a Django formset with Ajax](http://stackoverflow.com/questions/501719/dynamically-adding-a-form-to-a-django-formset-with-ajax) –  Sep 12 '15 at 05:14

1 Answers1

3

You can use javascript to create forms, then use Django's formset to handle the forms.

Here is a similar question with code example

Community
  • 1
  • 1
sharkfin
  • 3,827
  • 4
  • 23
  • 22