There is a case where I need to reuse the same ModelForm (The name's EngagementForm) in several cases, but wanted to disable some of the fields depends on the case. So I applied disabled inside my forms.py:
# Override Field Initialisation, used for disabling fields
def __init__(self, *args, **kwargs):
schedule_check = kwargs.pop('schedule', False)
super(EngagementForm, self).__init__(*args, **kwargs)
# If schedule argument set to True, disable the following fields
if schedule_check:
fields = (
'project_code',
'project_name',
'user_credential',
)
for i in fields:
self.fields[i].disabled = True
self.fields[i].required = False
However, Django throws validation error when I perform submit. The form.is_valid() returns False, and while inspecting errors using Pdb I saw this:
(Pdb) form.errors
{'project_code': ['This field is required.'],
'project_name': ['This field is required.'],
'user_credential': ['This field is required.']}
Check for their values, seems like disabled took away their values (or I might wrong here):
(Pdb) form['project_code'].value()
(Pdb)
I've tried few solutions found online (including feeding in initial values for each fields) yet none of these could fix the issue here.
FYI, this is the code in views.py:
def schedule_form(request, pk):
engagement = get_object_or_404(Engagement, pk=pk)
if request.method == "GET":
context = {
'title': "Schedule Task",
'form': EngagementForm(
instance=engagement,
schedule=True,
),
}
return render(request, 'forms/engagement_form.html', context)
else: # POST request
form = EngagementForm(request.POST, instance=engagement)
# Django thinks the form is invalid #
if form.is_valid():
form.save(update_fields=['schedule_date'])
return redirect('index')
else:
# Shows error message
# Django executed this block upon submit #
Much appreciated if I can get help from you guys, at least I should know what did I miss here.