Django:内联创建M2M关系

时间:2013-02-15 13:19:37

标签: django django-models django-forms

我正在尝试使用“链接”模型的表单集创建视图。问题是,在每种形式中,我希望用户不仅可以从已经创建的TargetLink对象中进行选择,而且可以内联编辑它们。

class ClientUrl(models.Model):
    client = models.ForeignKey(UpstreamClientModel, null=True)
    url = models.URLField(unique=True, null=False)
    active = models.BooleanField(default=True)

    def __unicode__(self):
        return self.url

    class Meta:
        verbose_name = 'url'
        ordering = ['url']

KEYWORD_TYPES = (
    ('PN', 'Pending'),
    ('MN', 'Money'),
    ('BR', 'Brand'),
    ('LT', 'Long Tail'),
)

class ClientKeyword(models.Model):
    client = models.ForeignKey(UpstreamClientModel, null=True)
    kw_type = models.CharField('keyword type', max_length=2, 
                choices=KEYWORD_TYPES, default='LT')
    keyword = models.CharField(max_length=150, unique=False)
    directions = models.CharField(max_length=200, blank=True, 
            help_text='e.g: 25 chars, use "affordable rental cars"')

    def __unicode__(self):
        return self.keyword

    class Meta:
        ordering = ['keyword', ]
        unique_together = ('client', 'keyword')

class TargetLink(models.Model):
    keyword = models.ForeignKey(ClientKeyword, related_name='target_links')
    url = models.ForeignKey(ClientUrl, related_name='target_links')

    def __unicode__(self):
        return '{0}:{1}'.format(self.keyword, self.url)

class Link(models.Model):
    client = models.ForeignKey(UpstreamClientModel, related_name='links')
    target = models.ForeignKey(Target, related_name='links')
    user = models.ForeignKey(User, blank=True, null=True, related_name='links')
    link_type = models.ForeignKey(LinkType, related_name='links')
    site = models.ForeignKey(Site, blank=True, null=True, 
                related_name='links')
    site_url = models.URLField(blank=True, 
            help_text='leave blank until url is live')
    month = models.DateField(blank=True, null=True)
    target_links = models.ManyToManyField(TargetLink, related_name='links')

我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

一种方法可能是在TargetLinks的formset之外创建一个表单,并使用Knockout.js或其他客户端框架将TargetLinks的更新选项推送到表单集中的target_links字段。