在Django admin中添加和更改表单时,以不同方式覆盖外键的默认表单字段

时间:2015-11-03 15:06:31

标签: django django-admin

我在ModelAdmin上使用formfield_for_foreignkey方法来覆盖外键的默认表单字段。它的工作完美。是否有可能为添加和更改表单而不同地覆盖表单域?

def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "idea":
        editor_group = Group.objects.filter(id=2).first()
        editors = AuthUser.objects.filter(groups=editor_group)
        if editors:
            f = FeaturedIdea.objects.all().values_list('idea__id', flat=True)
            kwargs["queryset"] = Idea.objects.filter(creator__in=editors).exclude(id__in=f)
        else:
            kwargs["queryset"] = Idea.objects.none()
    return super(FeaturedIdeaAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

我的FeaturedIdea模型是:

class FeaturedIdea(models.Model):

""" Model to create featured ideas """

idea = models.ForeignKey(Idea)
is_active = models.BooleanField(default=False)

在FeaturedIdea的更改形式上,我想展示当前的特色创意。

0 个答案:

没有答案