I try to display and add comment using Django admin, but Comment model use GenericForeignKey reference.
# in model.py
class Comment(models.Model):
type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
object = generic.GenericForeignKey('type')
text = models.TextField()
# in admin.py
class CommentAdmin(admin.ModelAdmin):
list_display = ('type', 'object', 'text')
fields = ('type', 'object', 'text')
admin.site.register(Comment, CommentAdmin)
But Django generate error:
‘CommentAdmin.fields’ refers to field ‘object’ that is missing from
the form.
How to fix it?
The
GenericForeignKeyisn’t a field in the database; it’s a helper to enable you with an api for the object you have defined through settingobject_idandtype, therefore you don’t need it in your form.To fix it, simply take it out and put in object_id: