Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Created February 26, 2018 14:36
Show Gist options
  • Save LowerDeez/b05b266a18a1cde5908507ed19718a0a to your computer and use it in GitHub Desktop.
Save LowerDeez/b05b266a18a1cde5908507ed19718a0a to your computer and use it in GitHub Desktop.
Django. How add to form extra fields
class MyForm(forms.Form):
...
def __init__(self, *args, **kwargs):
extra_fields = kwargs.pop('extra', 0)
super().__init__(*args, **kwargs)
if extra_fields and int(extra_fields) > 0:
for index in range(int(extra_fields)):
# generate extra fields in the number specified via extra_fields
self.fields['my_field{index}'.format(index=index+1)] = \
forms.CharField()
def get(self, request, *args, **kwargs):
form = self.form_class(
request.GET,
extra=request.GET.get('extra_field_count', 0)
)
if form.is_valid():
form_data = form.cleaned_data
response = ...
return JsonResponse(response, safe=False)
else:
return JsonResponse(form.errors)
return super().get(request, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment