On Wed, Sep 10, 2008 at 6:59 AM, Michel Thadeu Sabchuk
<[EMAIL PROTECTED]> wrote:
>
> Hi guys,
>
> What is the best way to work with 2 models on the same forms? Suppose
> I have the following case:
>
> class Profile(models.Models):
>    user = models.ForeignKey(User)
>    some_data = models.CharField()
>
> How can I add a profile and a user on the same form using ModelForm? I
> used to do:
>
> class ProfileForm(models.ModelForm):
>    class Meta:
>        model = Profile
>    first_name = models.CharField()
>    last_name = models.CharField()
>    email = models.EmailField()

Use 2 separate ModelForms. One for each model. If the 2 models happen
to have overlapping field names, you can use the 'prefix' argument to
the form to avoid name collisions.

One bit to be wary of is calling form.is_valid() in your view. If you
have something like this:

if user_form.is_valid() and profile_form.is_valid():
    # save stuff

and user_form.is_valid is False, profile_form.is_valid() won't be
called. I usually write a function called all_valid(list_of_forms)
that calls is_valid() on each form and returns False if any of them
fail.

Joseph

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