Skip to content

Instantly share code, notes, and snippets.

@mcantelon
Last active December 14, 2015 13:38
Show Gist options
  • Save mcantelon/5094314 to your computer and use it in GitHub Desktop.
Save mcantelon/5094314 to your computer and use it in GitHub Desktop.
Django dynamic form:
forms.py:
class ProcessingForm(forms.Form):
def __init__(self, *args, **kwargs):
if 'extra' in kwargs:
extra = kwargs.pop('extra')
super(ProcessingForm, self).__init__(*args, **kwargs)
if 'extra' in locals():
for i, question in enumerate(extra):
self.fields['custom_%s' % i] = forms.CharField(label=question)
def extra_answers(self):
for name, value in self.cleaned_data.items():
if name.startswith('custom_'):
yield (self.fields[name].label, value)
views.py:
def some_view(request):
fields = ['field', 'another']
if request.method == 'POST':
form = ProcessingForm(request.POST, extra=fields)
if form.is_valid():
for (name, value) in form.extra_answers():
# use name, value to do something
pass
else:
form = ProcessingForm(extra=fields)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment