Django form linking 2 multi-field models

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 relationship between the two models when adding a new record. It works:

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

The form includes both a name and an event, which allows me to create a new Actor and at the same time associate it with an existing event.

On the back

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

This form does not include an association of actors. Therefore, I can only create a new event. I cannot simultaneously link it to an existing actor.

I tried to create an inline set of forms:

  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 is not too surprising. Inlineformset worked for a different set of models that I had, but this is a different example. I think I'm wrong.

The general question: how to create a form that allows me to create a new event and associate it with an existing actor?

+3
source share
1 answer

Personally, I would put ManyToMany on the Event, but each of them ...

As for how to do this, you need to write your own ModelForm (not a built-in set of forms), let it be called EventForm. It would handle all of your event fields and also have a ModelChoiceField or ModelMultipleChoiceField to allow the selection of actor (s). Then, in your opinion, you would separate the processing of Event fields and ForeignKey / M2M fields.

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

+1
source

Source: https://habr.com/ru/post/1305623/


All Articles