On 25/01/07, Håkan Johansson <[EMAIL PROTECTED]> wrote:
>
> On 20 jan 2007, at 17:36, [EMAIL PROTECTED] wrote:
> >
> > Håkan Johansson wrote:
> >
> >> 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')

I'm curious about this method. How do you use these forms in your
view? More specifically: how do you validate the request.POST data?

Felix

P.S.

I've come up with some spaghetti code which will create a new form
class for an instance (in a similar way to form_for_instance but using
a custom form). It's not pretty but it allows me to do something like
this:

def add(request, id):
    if id is not None:
        obj = Obj.objects.get(id)
        form = custom_form_for_instance(obj)
    else:
        form = empty_custom_form()

    if request.POST:
        new_form = form(request.POST)
        if new_form.is_valid():
            new_form.save()
            # redirect etc
    new_form = form()
    render_to_response('template.html', {'form': new_form})

Now I'm not particularly happy with how custom_form_for_instance works
but it does and it let's me use the generated form in a similar way to
form_for_instance.

--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to