Hello!
I have been making use of GenericForeignKeys in some software I’ve been working on and I became frustrated with the Django Admin experience with these fields. I find the ContentType input and object id inputs to be really error prone for configuring the model.
I built a package that will replace those inputs with a single select field that only has options for the models that actually have GenericRelations back to your model so that it’s easier to work with. It should work for any number of GenericForeignKeys on your model and it allows you to filter the querysets of the related models. All you need to do is use GenericFKAdmininstead of ModelAdminand you’re good to go.
I’d love to get some feedback and have folks try it out if they make use of this feature!
Repo: GitHub - mikespallino/django-genericfkadmin: No frills GenericForeignKeys for your Django Admin · GitHub
Documentation: Django GenFKAdmin documentation — Django GenFKAdmin 0.3.2 documentation
Thanks for sharing this. I’ve run into the same friction with GenericForeignKey fields in the admin. Having to choose a ContentType and then enter an object ID manually makes it easy to select the wrong combination.
For example, say comments can be attached to either an article or a video. Each target model can declare a GenericRelation, and the comment admin can use GenericFKAdmin:
# models.py
from django.contrib.contenttypes.fields import (
GenericForeignKey,
GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Comment(models.Model):
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE,
)
object_id = models.PositiveBigIntegerField()
content_object = GenericForeignKey()
text = models.TextField()
class Article(models.Model):
title = models.CharField(max_length=200)
comments = GenericRelation(Comment)
class Video(models.Model):
title = models.CharField(max_length=200)
comments = GenericRelation(Comment)
# admin.py
from django.contrib import admin
from genericfkadmin.admin import GenericFKAdmin
from .models import Comment
@admin.register(Comment)
class CommentAdmin(GenericFKAdmin):
pass
That gives admins a more guided way to choose the related object instead of typing an ID. The queryset filtering support sounds useful too, especially when only some related objects should be available. I’ll give it a try thanks for putting it together!
1 Like
Yes, exactly! Thanks for giving this a look! If you come across any problems when you try it out please raise an issue on github and I’ll pick it up. I have an idea to extend this with an autocomplete widget as well instead of the select with option groups, but I haven’t had a chance to work on it just yet.