On Sun, Feb 6, 2011 at 4:25 PM, Nate Reed <natereed....@gmail.com> wrote: > I posted this question on StackOverflow, too. I have defined a Model > with a ManyToManyField, and I want the field to show the values joined > by spaces, for example: > > <input type="text" name="foo" value="val1 val2 val3"/> > > I have defined the form to use CharField to represent the multiple values: > > class MyForm(ModelForm): > foo = CharField(label='Foo') > class Meta: > model = MyModel > > Instead of showing the values separated by spaces, the input field > shows this instead: > > [u'val1', u'val2', u'val3'] > > How can I override this behavior? My understanding is that widgets > are responsible for rendering the input. Is there an example of a > custom widget that does something like this? > > Nate >
You have a related problem in terms of what you want to have happen when the form is submitted. The string that you get needs to be converted to objects (or their id's) before you can save them to the DB, and a representation of the id probably isn't what you're expecting to show in the field. CharField is mostly suitable for submitting a character string, typically stored in the DB as a character string. Relation fields are more amenable to a (multi-)select field or radio buttons (check boxes for multiple valued fields). You could create a custom form field, if this scheme is truly what you wish. You can also render the desired input within your form by hand, instead of expecting the from object's as_p(), etc. to render it for you. You will then also need to check the submitted value in the POST or GET data, since the form object doesn't know about it. The template language is strong enough to render what you want if you pass the related object manager to the template, but it is a bit hairy for a template, so I'd suggest having your view function calculate the desire value string for the input, and pass that instead. When you parse the posted value, you will still need to look up the objects somehow from the submitted value. Bill -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@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.