On Thu, 2009-01-29 at 03:56 -0800, Markus Bertheau wrote:
> Hi,
> 
> I need a registration form that allows the user to input several
> models. Now just creating two ModelForms and letting a third class
> inherit from them doesn't work, the fields of one model don't show. Is
> there another way to reuse the part of ModelForms that create
> FormFields from ModelFields?

I'd avoid trying to make them into a single form class.

A Form subclass in Django (which includes ModelForms) is only a part of
the HTML-side form. So you can use multiple Form subclasses to generate
a single HTML form.

Furthermore, when you pass data to a form for validation, it ignores any
input that isn't part of the form, so you can pass request.POST to both
forms without having to work out which fields belong to which form. You
might well want to investigate the "prefix" option ([1]) if there's a
chance of field name collision.

By way of example (completely untested, but likely to be close):

        def my_view(request):
           if request.method == "POST":
              form_a = ModelAForm(request.POST, prefix="a")
              form_b = ModelBForm(request.POST, prefix="b")
              if form_a.is_valid() and form_b.is_valid():
                   # ....
                   return http.HttpResponseRedirect(...)
           else:
              form_a = ModelAForm(prefix="a")
              form_b = ModelBForm(prefix="b")
        
           data = {
              "form_a": form_a,
              "form_b": form_b,
           }
           return render_to_response('form.html', data)
        
If you're doing this with N models (for some large-ish value of N), it's
easy enough to make a loop to create the forms and check validity, etc.
For a different example, see [2].

[1]
http://docs.djangoproject.com/en/dev/ref/forms/api/#prefixes-for-forms
[2]
http://www.pointy-stick.com/blog/2008/01/06/django-tip-complex-forms/

Regards,
Malcolm


--~--~---------~--~----~------------~-------~--~----~
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