[Fixed]-Django template isn't rendering dynamic form errors

0👍

Daniel Roseman was correct in that I need to pass ‘submission’ into the form when I instantiate the form on POST. But there were still two other problems. First, I need to instantiate the form inside the else block. If this isn’t done and the form doesn’t validate, then you’re passing an unbound form back to the viewer and any errors won’t be displayed. Also, it isn’t necessary to pass ‘submission’ to the form when you instantiate it here:

...
else:
    form = FeedbackQuestionResponseForm()
context = {...}
...

The next problem was that the order of my statements inside the init method was incorrect. It appears that I needed to execute ‘super()’ before trying to reference the ‘response_text’ field. I’ll need to locate and study this method in the Django source code to understand exactly why. In any case, this works:

def __init__(self, *args, **kwargs):
    if 'submission' in kwargs:
        submission = kwargs.pop('submission')
    else:
        submission = False
    super(FeedbackQuestionResponseForm, self).__init__(*args, **kwargs)
    if submission:
        if submission.submission_type == 'question':
            self.fields['response_text'].required = True
        else:
            self.fields['response_text'].required = False

When the above changes are implemented, the form will make the response_text field required if the user submits a question and an error will be displayed if the admin doesn’t enter a response before submitting the form. Many thanks again to Daniel for getting me back on track towards finding a solution.

👤Jim

1👍

You’re not passing submission into the form when you instantiate it on POST, so the required attribute is never being set.

Leave a comment