The way to do that is to use the 'initial' keyword argument when you instantiate the form, to which you supply a dictionary of field name : initial value e.g.:
  form = KingModelForm(initial={'first': 'First Name', 'last': 'Surname'})

How you split the name will depend on how you're storing it. Assuming you have the name in "First Names Surname" format, this should do it:
def split_name(name):
    """Return a dictionary of first and last names from the given name."""
    splitname = name.split()    # splits on white space
    last = splitname[-1]
    first_names = splitname[:-1] # Allows for more than one first name
    first = ' '.join(first_names)
    return dict(first=first, last=last)

Then:
 form = KingModelForm(initial=split_name(name))

Just a thought, is there any reason not to store first and last as separate fields, and join the names when you present them on screen / in reports? That would save having to make assumptions about the number of first and surnames people enter (someone could enter 'Barton Hartley' as a double-barreled surname for example).

Regards,

Nick Booker

On 11/02/10 16:27, Derek wrote:
I like to set the value/s of a field in a form before displaying it.

A rather silly example (to illustrate the principle) :

class King(models.Model):
     name = models.CharField(max_length=250, blank=False)

class KingModelForm ( forms.ModelForm ):
     first  = forms.CharField( label = 'Foo', required=True)
     last  = forms.CharField( label = 'Foo', required=True)

I need to split the name field up and allocate it to first & last
before displaying the form for editing.

(When saving the form, these values will be combined, but that
part can be done via the save_form() method.)

Any help with this is appreciated.

Thanks
Derek

--
You received this message because you are subscribed to the Google
Groups "Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to