'Formset with request.post not initializing correctly
I am having an issue using formsets and request.POST. Whenever I initialize the formset without request.POST it works as intended, but will not send the data through as the form is never valid. If I include request.POST (as I have done on all my other forms in the view) the formset doesn't seem to initialize correctly. No data gets through, I can't see any form fields, and I get a html warning saying:
(Hidden field TOTAL_FORMS) This field is required.
(Hidden field INITIAL_FORMS) This field is required.
Here is a very simplified version of what I am doing in my project. This is bare minimum and the project itself is much more involved. But this should be the heart of the problem I am having.
The intent of this very basic form is that my formset would have 3 forms, each one initialized with a letter, 'a', then 'b', then 'c'.
views.py
def MyView(request):
my_formset = formset_factory(my_form)
my_list = ['a', 'b', 'c']
if request.method == 'POST':
my_formset = formset(request.POST, initial=[{'field1':x} for x in my_list]) #If I remove 'request.POST' then the form initializes correctly, but will never pass .is_valid()
if my_formset.is_valid():
print('valid')
else:
print('invalid')
else:
my_formset = formset(initial=[{'field1':x} for x in my_list])
ctx = {'formset' = my_formset}
return render(request, 'template.html', ctx)
forms.py
class my_form(forms.Form):
field1 = forms.CharField(required=True)
template
<form method="POST">
{% csrf_token %}
{{formset.management_form}}
{% for form in formset %}
{{form.field1}}
{% endfor %}
</form>
When including the request.POST in the initialization of my_formset, it seems like it kills the form entirely.
When I run it without the request.POST in that line, it works. The form comes through and the initial value is there.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
