Created
February 26, 2018 14:36
-
-
Save LowerDeez/b05b266a18a1cde5908507ed19718a0a to your computer and use it in GitHub Desktop.
Django. How add to form extra fields
This file contains 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
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() |
This file contains 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
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