Last active
December 14, 2015 13:38
-
-
Save mcantelon/5094314 to your computer and use it in GitHub Desktop.
Django dynamic form:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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