I have a form that I want to be validated before showing it initially. Basically the behavior I’m going for is that when user opens the form, the initial values (pulled from the object instance) are already checked, and if invalid, marked as such with errors attached.
The idea is to have two forms:
def DraftForm(forms.ModelForm):
class Meta:
model = Project
def FinalForm(DraftForm):
def __init__(self, *args, **kwargs):
super(FinalForm, self).__init__(*args, **kwargs)
self.fields['text'].required = True
The first one is used when editing a draft, the second is used to checked if all fields required to publish are filled in etc.
I thought something like this in the “edit project” view would work and make the initial form show with errors:
# redirected from some other form, so no POST at this point:
if request.session.get('trying_to_publish', False):
form = FinalForm(instance=project)
form.is_valid()
else:
form = DraftForm(instance=project)
...
but no; full_clean() doesn’t trigger the errors as well. Any ideas?
You need the form to be bound. In place of the request object, you can just use an empty dictionary.
The is_valid() docs help explain this a little (if you knew what you are looking for). The form has to be bound before it can be validated. Even a form that is passed an empty dictionary becomes bound.