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?

4
  • 1
    seems you need formset Commented May 15, 2012 at 4:05
  • that looks promising ... will look into formsets now..thanks! Commented May 15, 2012 at 4: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? Commented May 15, 2012 at 4:31
  • possible duplicate of Dynamically adding a form to a Django formset with Ajax Commented Sep 12, 2015 at 5:14

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.