While working on a complex form using 'newforms' I had some problem with 'initial' data. I have multiple forms using the 'prefix' argument to get different keys for them.

As far as I know (*please* correct me if I am wrong) the only way to set initial data dynamically is to create the fields in __init__.

Form example ('obj' is object to get initial data from):
  >>> import django.newforms as forms
  >>> class DaForm(forms.Form):
  ...     def __init__(self, obj, *args, **kw):
  ...         super(DaForm, self).__init__(*args, **kw)
  ...         self.fields['time'] = forms.TimeField(initial=obj.time)
  ...         self.fields['name'] = forms.CharField(initial=obj.name)
  ...         # etc.

  >>> # No form data as we are viewing the objects.
  >>> form1 = DaForm(obj1, prefix='obj1')
  >>> form2 = DaForm(obj2, prefix='obj2')

The problem with the example above is that the initial data for 'form1' is overwritten by the initial data in 'form2' so both forms give the same output. This happens because 'self.fields' belongs to the class and not the object instance.

To solve this, you need to override the 'fields' attribute of the object:
  >>> import django.newforms as forms
  >>> from django.utils.datastructures import SortedDict
  >>> class DaForm(forms.Form):
  ...     def __init__(self, obj, *args, **kw):
  ...         super(DaForm, self).__init__(*args, **kw)
  ...         self.fields = SortedDict()
  ...         self.fields['time'] = forms.TimeField(initial=obj.time)
  ...         self.fields['name'] = forms.CharField(initial=obj.name)
  ...         # etc.

If you have static fields combined with dynamic fields you will need to repopulate 'self.fields' from the class version. Using 'self.fields = self.fields.copy()' does not work as it returns a normal 'dict' and not a 'SortedDict'.



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to