Django表单通过多对多字段链接2个模型

标签 django forms many-to-many inline

我有两个模型:

 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)

我想创建一个表单,允许我在添加新条目时识别两个模型之间的链接。这有效:
 class ActorForm(forms.ModelForm):
     class Meta:
           model = Actor

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

另一方面,
 class EventForm(forms.ModelForm):
     class Meta:
           model = Event

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

我试图创建一个内联表单集:
 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 适用于我拥有的另一组模型,但这是一个不同的示例。我想我完全错了。

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

最佳答案

就个人而言,我会首先将 ManyToMany 放在 Event 上,但对于每个人来说...

至于怎么做,你会想写一个自定义的 ModelForm(不是内联表单集),我们称之为 EventForm。它将处理您的所有事件字段,并且还会有 ModelChoiceFieldModelMultipleChoiceField允许选择所涉及的参与者。然后在您的 View 中,您将拆分事件字段和 ForeignKey/M2M 字段的处理。

有道理? alt text http://sonicloft.net/im/52

关于Django表单通过多对多字段链接2个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2503243/

相关文章:

python - fabric 不适用于我的 python/django 代码

jquery - 如何使用 python 框架 Splinter 与 jQuery colorbox 交互?

javascript - 安全的 html 表单变量

c# - 多对多导航属性为空

NHibernate ManyToMany 和急切加载 : strange resultset for SetFetchmode combined with SetResultTransformer and SetMaxResult

python - Django 国际化---编译消息错误 :AttributeError: module 'locale' has no attribute 'normalize'

python - django send_mail() 函数需要几分钟

php - Jquery/Ajax 表单提交(enctype ="multipart/form-data")。为什么 'contentType:False' 在 PHP 中会导致 undefined index ?

python - Django表单和html表单有什么区别

django 在模型上具有相同关系的多个多对多字段