The Importance of the initial argument in Django newforms library

I like Django a lot. In fact I am in the middle of converting a large J2EE application to Django. Sometimes I run into a problem using it, and knowing Django, I know there is a good solution. To find the solution however, sometimes require very careful reading of the documentation. Case in point. The solution here is completely documented in the Django online documentation. But perhaps, at least to me, not so obvious.

The problem:

A typical usage: display a form to add some data to the application. I need to include a hidden field and populate it with a value (obviously, since it is a hidden field, the only value is going to come from the application).

If you simply put the value in the dictionary to the form's constructor in the "GET" code path of your view handler, you will likely trigger the form's validation logic, and complain if you have any other normal fields that are required field.

The Solution:

The solution is to use the "initial" argument to the form's constructor, not to use the bounded data dictionary. The documentation discuss the "initial" argument as part of the unbounded newforms support, and I (wrongly assumed) normally do not think of my forms are unbounded. But they are, in the GET part of the handler.

Code Sample:

Class MyForm(forms.Form):
    important_field = forms.CharField(max_length=32,required=True)
    my_secret_field = forms.IntegerField(widget=forms.HiddenInput(),required=True)

def my_view(request):
    if request.method == 'POST':
        # do post stuff...
        # GET, do this:
        form = MyForm(initial={'my_secret_field':42})
        # do NOT do this, because form will be displayed with
        # error: important_field is required on first display:
        # form = MyForm({'my_secret_field':42})