4

我们有一个包含报纸文章列表的 Django 应用程序。每篇文章都与“发言人”和“公司”(文章中提到的公司)都存在 m2m 关系。

目前,用于创建新文章的 Add Article 页面非常接近我们想要的——它只是普通的 Django Admin,我们使用 filter_horizo​​ntal 来设置两个 m2m 关系。

下一步是在每个 m2m 关系上添加一个“评级”字段作为中间字段。

所以,我们的 models.py 的一个例子

class Article(models.Model):
    title = models.CharField(max_length=100)
    publication_date = models.DateField()
    entry_date = models.DateField(auto_now_add=True)
    abstract = models.TextField() # Can we restrict this to 450 characters?
    category = models.ForeignKey(Category)
    subject = models.ForeignKey(Subject)
    weekly_summary = models.BooleanField(help_text = 'Should this article be included in the weekly summary?')
    source_publication = models.ForeignKey(Publication)
    page_number = models.CharField(max_length=30)
    article_softcopy = models.FileField(upload_to='article_scans', null=True, blank=True, help_text='Optionally upload a soft-copy (scan) of the article.')
    url = models.URLField(null=True, blank=True, help_text = 'Enter a URL for the article. Include the protocl (e.g. http)')
    firm = models.ManyToManyField(Firm, null=True, blank=True, through='FirmRating')
    spokesperson = models.ManyToManyField(Spokeperson, null=True, blank=True, through='SpokespersonRating')

    def __unicode__(self):
        return self.title

class Firm(models.Model):
    name = models.CharField(max_length=50, unique=True)
    homepage = models.URLField(verify_exists=False, help_text='Enter the homepage of the firm. Include the protocol (e.g. http)')

    def __unicode__(self):
        return self.name

    class Meta:
        ordering = ['name']

class Spokeperson(models.Model):
    title = models.CharField(max_length=100)
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.first_name + ' ' + self.last_name

    class Meta:
        ordering = ['last_name', 'first_name']

class FirmRating(models.Model):
    firm = models.ForeignKey(Firm)
    article = models.ForeignKey(Article)
    rating = models.IntegerField()

class SpokespersonRating(models.Model):
    firm = models.ForeignKey(Spokesperson)
    article = models.ForeignKey(Article)
    rating = models.IntegerField()

这里的问题是,一旦我们将公司和发言人字段更改为“通过”并使用中介,我们的添加文章页面不再有 filter_horizo​​ntal 控件来将公司/发言人关系添加到文章中——它们完全消失了。你根本看不到它们。我不知道为什么会这样。

我希望有某种方法可以继续使用很酷的 filter_horizo​​ntal 小部件来设置关系,并以某种方式在其下方嵌入另一个字段来设置评级。但是,我不确定如何在仍然利用 Django 管理员的同时做到这一点。

我在这里看到一篇关于在 Django admin 中覆盖单个小部件的文章:

http://www.fictitiousnonsense.com/archives/22

但是,我不确定该方法是否仍然有效,并且我不确定是否将其应用到此处,将 FK 用于中间模型(那么它基本上是内联的?)。

当然有一个简单的方法来做这一切?

干杯,维克多

4

1 回答 1

8

问题是管理员的方法formfield_for_manytomany没有django.contrib.admin.options返回带有中间模型的多对多字段的表单字段!http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/options.py#L157

您必须在 ModelAdmin 中覆盖此方法:

def formfield_for_manytomany(self, db_field, request=None, **kwargs):
    """
    Get a form Field for a ManyToManyField.
    """
    # If it uses an intermediary model that isn't auto created, don't show
    # a field in admin.
    if not db_field.rel.through._meta.auto_created:
        return None    # return something suitable for your needs here!
    db = kwargs.get('using')

    if db_field.name in self.raw_id_fields:
        kwargs['widget'] = widgets.ManyToManyRawIdWidget(db_field.rel, using=db)
        kwargs['help_text'] = ''
    elif db_field.name in (list(self.filter_vertical) + list(self.filter_horizontal)):
        kwargs['widget'] = widgets.FilteredSelectMultiple(db_field.verbose_name, (db_field.name in self.filter_vertical))
于 2010-06-24T11:05:22.997 回答