9
votes

My Complete_Book model has a foreign key to Book. Book is something I'm using from an installed app (so, an 'outside app') I would like to be able to edit/create a 'Book' directly from the Complete_Book admin. Is this possible? I haven't been able to use inlines, as my foreign key relationship is 'backwards' from what inline allows.

My problem is the same as that explained in this question (Django admin inline display but foreign key has opposite relation) but I cannot refactor my models as suggested in that answer. Is there any other way? Thank you for your help!

models.py

class Complete_Book(models.Model):
    topic = models.ForeignKey('topic')
    book = models.ForeignKey(Book)
    is_primary = models.BooleanField()
    subprogram_name = models.CharField(max_length = 256, blank=True)

class Book(models.Model):
    title = models.CharField(max_length=512)
    authors = models.CharField(max_length=2048)
    year = models.PositiveIntegerField(max_length=4)
2

2 Answers

7
votes

django_reverse_admin is a django module to solve this problem of needing inlines where the relationships are the 'wrong' direction.

You'll need to add it to your requirements.txt and then import it:

admin.py

from django_reverse_admin import ReverseModelAdmin

class Complete_Book(ReverseModelAdmin):
    # usual admin stuff goes here
    inline_type = 'tabular'  # or could be 'stacked'
    inline_reverse = ['book']  # could do [('book', {'fields': ['title', 'authors'})] if you only wanted to show certain fields in the create admin

admin.site.register(Book, Complete_Book)
2
votes

Yes, this is actually quite easy. Just be sure to register a ModelAdmin for Book and admin will add a + button to the Complete_Book admin that will allow you to create a new Book.