Django Form Disabled Select Option Values Not Submitted Even When They are Enabled with JavaScript Before Submission
My HTML displays about 20 or more forms via modelformset_factory
and each having a preselected staff name (so this is disabled in forms.py
). Staff name is primary key to Staff model, so I don't want all their names be available for selection. Logged in user have some staff assigned and so they are only required to enter phone number and address. The disabled fields are enabled with Javascript before the form is submitted but I still get {'staff_name': ['This field is required.']}
error when the form is submitted.
Here are my codes:
forms.py
class StaffForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['staff_name'].disabled = True
views.py
class StaffModelFormSet(BaseModelFormSet):
def clean(self):
super().clean()
print(self.errors)
class StaffEntryView(LoginRequiredMixin, FormView):
def post(self, request, *args, **kwargs):
StaffFormSet = modelformset_factory(Staff, form=StaffForm, formset=StaffModelFormSet)
submitted_form = StaffFormSet(request.POST)
if submitted_form.is_valid():
self.form_valid(submitted_form)
print("This form is valid, Sir!")
else:
self.form_invalid(submitted_form)
print("This is not a valid form.")
template.html
<form method="post" class="form-control" id="staff_form" name="staff-form" onsubmit="enablePath();">
<!-- form details goes here -->
<tbody>
{% for form in formset %}
<tr class="table-striped">
<td>{{ form.staff_name }}</td>
<td>{{ form.phone }}</td>
<td>{{ form.address }}</td>
</tr>
{% endfor %}
</tbody>
script.js
function enablePath(e) {
var options = document.getElementsByTagName('select');
for (var i=0, iLen=options.length; i<iLen; i++) {
options[i].disabled = false;
}