Django form linking 2 models by many to many field.

Posted by Ed on Stack Overflow See other posts from Stack Overflow or by Ed
Published on 2010-03-23T20:11:34Z Indexed on 2010/03/23 20:13 UTC
Read the original article Hit count: 369

Filed under:
|
|
|

I have two models:

 class Actor(models.Model):
     name = models.CharField(max_length=30, unique = True)
     event = models.ManyToManyField(Event, blank=True, null=True)

 class Event(models.Model):
     name = models.CharField(max_length=30, unique = True)
     long_description = models.TextField(blank=True, null=True)

I want to create a form that allows me to identify the link between the two models when I add a new entry. This works:

 class ActorForm(forms.ModelForm):
     class Meta:
           model = Actor

The form includes both name and event, allowing me to create a new Actor and simultaneous link it to an existing Event.

On the flipside,

 class EventForm(forms.ModelForm):
     class Meta:
           model = Event

This form does not include an actor association. So I am only able to create a new Event. I can't simultaneously link it to an existing Actor.

I tried to create an inline formset:

 EventFormSet = forms.models.inlineformset_factory(Event,
       Actor,
       can_delete = False,
       extra = 2,
       form = ActorForm)

but I get an error

<'class ctg.dtb.models.Actor'> has no ForeignKey to <'class ctg.dtb.models.Event'>

This isn't too surprising. The inlineformset worked for another set of models I had, but this is a different example. I think I'm going about it entirely wrong.

Overall question: How can I create a form that allows me to create a new Event and link it to an existing Actor?

© Stack Overflow or respective owner

Related posts about django

Related posts about forms