I have a form with 4 fields.
class data_collect_form(forms.Form):
data_entry1 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0}))
data_entry2 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0})
data_entry3 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0})
data_entry4 = forms.IntegerField(widget = forms.NumberInput(attrs={"class":"form-control","initial":0}))
Based on the argument "number_of_fields" in the view, I would like to delete last fields of this form.
Here is the view:
def add_submission(request, number_of_fields ):
#delete number of fields of data_collect_form according to number_of_fields argument
if request.method == 'POST':
form2 = data_collect_form(request.POST)
else:
form2 = data_collect_form()
return render(request, 'main/second.html',{"form2":form2})
I am sure it should be possible with the __init__
method, but I do not have understanding on writing it correctly.
CodePudding user response:
should be pretty straight forward like this:
number_of_fields = 3
form2 = data_collect_form(number_of_fields)
init for class data_collect_form
def __init__(self, number_of_fields, *args, **kwargs):
super(data_collect_form, self).__init__(*args, **kwargs)
if number_of_fields < 4:
self.fields.pop('data_entry4')