Using ModelForm to edit ManyToMany in both directions?

209 views
Skip to first unread message

Wilberoni

unread,
Mar 26, 2010, 1:28:49 AM3/26/10
to Django users
I have a simple model that allows a volunteer to have many jobs and a
job to have many volunteers:

class Volunteer(models.Model):
jobs = models.ManyToManyField( 'Job', blank=True )


The following ModelForm displays a Multi-select widget so I can choose
all the jobs for a volunteer:

class VolunteerForm( ModelForm ):

class Meta:
model = Volunteer


This is some fairly basic Django. However, I'd also like to be able
to edit in the other direction -- from a Jobs form, I'd like to be
able to see a Multi-select widget containing all the volunteers who
have this job and select/unselect them. I can't quite wrap my brain
around this and I've found no clues by searching the web. Does Django
provide some facility to accomplish this or do I have to build
something from the ground up?

Thanks.
Wilb

Wilberoni

unread,
Mar 26, 2010, 8:58:06 AM3/26/10
to Django users
Clarification:

I'd like to see a Multi-select widget containing ALL the volunteers,
with those who currently have the job selected. I'd like to them be
able to select additional volunteers for that job or unselect existing
ones.

Wilb

jwil...@gmail.com

unread,
Mar 27, 2010, 1:02:22 AM3/27/10
to Django users
I believe the answer is to append a regular Form to the ModelForm) with a single ModelMultipleChoice field and use its queryset member to manage the selected volunteers manually.

I've found Django to be so good at just having everything I need, I was hoping there would be something out of the box for this as well.

Wilb

pjrh...@gmail.com

unread,
Mar 28, 2010, 4:29:57 PM3/28/10
to Django users

Thierry Chich

unread,
Mar 29, 2010, 2:50:57 AM3/29/10
to django...@googlegroups.com

Nice idea ! It will simplify my work.
Thanks to share it !


Le 28 mars 2010 à 22:29, "pjrh...@gmail.com" <pjrh...@gmail.com> a
écrit :

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

Wilberoni

unread,
Mar 29, 2010, 11:41:57 AM3/29/10
to Django users
That's fantastic! I did it using one of the alternatives he describes
(separate form with constructor/save code to manually select, extract
and set the ManyToMany) and it was fairly unpleasant.

Thanks for point this out.

Reply all
Reply to author
Forward
0 new messages