Django形式链接两个模型由多个到许多领域 [英] Django form linking 2 models by many to many field

查看:141
本文介绍了Django形式链接两个模型由多个到许多领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:

 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

该表单包括名称和事件,允许我创建一个新的Actor并将其同时链接到现有的事件

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

另外,

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

此表单不包括演员协会。所以我只能创建一个新的事件。我不能同时链接到现有的Actor。

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)

但是我收到错误

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

这并不奇怪。 inlineformset适用于另一套模型,但这是一个不同的例子。我想我完全错了。

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.

总体问题:我如何创建一个表单,让我创建一个新的事件并将其链接到现有的Actor ?

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

推荐答案

个人来说,我会把ManyToMany以事件开头,而是每一个自己的...

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

至于如何做,你想编写一个自定义的ModelForm(不是一个内联的formset),让我们称之为EventForm。它将处理所有事件的字段,并且还将具有 ModelChoiceField ModelMultipleChoiceField 以允许选择Actor (s)涉及。那么在你看来,你会拆分事件字段和ForeignKey / M2M字段的处理。

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.

有意义吗? alt text http://sonicloft.net/im/52

这篇关于Django形式链接两个模型由多个到许多领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆