Reputation: 31
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?
Upvotes: 1
Views: 3125
Reputation: 3857
You can use javascript to create forms, then use Django's formset to handle the forms.
Here is a similar question with code example
Upvotes: 3