Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing/Adding a Foreign Key object through inline display in the Django Admin

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)
like image 200
steph Avatar asked Jan 21 '15 20:01

steph


2 Answers

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)
like image 159
lynx Avatar answered Sep 21 '22 07:09

lynx


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.

like image 38
dylrei Avatar answered Sep 20 '22 07:09

dylrei