Search code examples
djangodjango-admindjango-grappelli

GenericForeignKey in admin


I try to use grappelli to get a widget for generic foreign key. This is what i need to get: http://code.google.com/p/django-grappelli/wiki/generic_2_1. I've got a model:

class Circuit(models.Model):
    circuit_id = models.PositiveIntegerField(verbose_name=_("Circuit ID"), blank=True, null=True)
    model = models.ForeignKey(Versiiplates, verbose_name=_("Model"))
    date_created = models.DateField(blank=True, null=True, verbose_name=_("Date Created"), default=datetime.date.today())
    manufacturer = models.ForeignKey(Manufacturer, null=True, blank=True, verbose_name="Производитель")
    manufacturer_comments = models.TextField(max_length=2500, null=True, blank=True, verbose_name="Комментарии производителя")
    keeper_type = models.ForeignKey(ContentType, blank=True, null=True, related_name="keeper_type")
    keeper_id = models.PositiveIntegerField(blank=True, null=True)
    keeper = generic.GenericForeignKey('keeper_type', 'keeper_id')
    status = models.PositiveIntegerField(verbose_name=_("Status"), choices=STATUS_TYPE, default=0)
    status_history = models.ManyToManyField(Status, blank=True, null=True)
    status_comment = models.TextField(max_length=2500, blank=True, null=True, verbose_name="Комментарий")

    def __unicode__(self):
        return u"%s #%d" % (self.model, self.circuit_id)

    class Meta:
        verbose_name = _("Circuit")
        verbose_name_plural = _("Circuits")

and AdminModel for it:

class CircuitAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {'fields': ['circuit_id', 'model', 'date_created']}),
        (_("Manufacturer"), {'fields':['manufacturer', 'manufacturer_comments']}),
        (_("Status"), {'fields': ['status', 'status_comment']})
    ]
    list_display = ('circuit_id', 'model', 'date_created', 'keeper', 'status')
    search_fields = ('circuit_id', )
    list_filter = ('model', 'status')
    related_lookup_fields = {
        'generic': [['keeper_type', 'keeper_id']]
    }

But there is still no widget for my GenericForeignKey in admin. And why in grapelli's example of using it there are two GenericForeignKey fields?


Solution

  • The answer is really simple. I just needed to add keeper_id and keeper_type fieldsets, like this:

    fieldsets = [
            (None, {'fields': ['circuit_id', 'model', 'date_created', 'keeper_type', 'keeper_id']}),
            (_("Manufacturer"), {'fields':['manufacturer', 'manufacturer_comments']}),
            (_("Status"), {'fields': ['status', 'status_comment']})
        ]