开发者

Django form linking 2 models by many to many field

开发者 https://www.devze.com 2022-12-23 18:11 出处:网络
I have two models: class Actor(models.Model): name = models.CharField(max_length=30, unique = True) event = models.ManyToManyField(Event, blank=True, null=True)

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?


Personally, I would put the ManyToMany on Event to begin with, but to each their own...

As for how to do it, you'd want to write a custom ModelForm (not an inline formset), let's call it EventForm. It would handle all of your event's fields and would also have a ModelChoiceField or ModelMultipleChoiceField to allow selection of the Actor(s) involved. Then in your view you would split out the processing of the Event fields and the ForeignKey/M2M field.

Make sense? alt text http://sonicloft.net/im/52

0

精彩评论

暂无评论...
验证码 换一张
取 消