1

I want to add fields dynamically in Django 1.8.

Here's my models.py

class Book(models.Model):
   title = models.CharField(max_length=100)

   def __str__(self):
        return self.title

class Author(models.Model):
   name = models.CharField(max_length=100)
   books = models.ManyToManyField(Book)

   def __str__(self):
        return self.name

Here's my admin.py

class AuthorAdmin(admin.ModelAdmin):
admin.site.register(Author, AuthorAdmin)

class BookAdmin(admin.ModelAdmin):
admin.site.register(Book, BookAdmin)

Here's how it looks now:

enter image description here

I've tried to use Inline, but I can only add a new book also.

I want to be able to add many books to one author dynamically. Something like this: enter image description here

How can I do this?

Edit:

I've changed AuthorAdmin to this:

class AuthorAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.ManyToManyField: {'widget': CheckboxSelectMultiple},
    }
admin.site.register(Author, AuthorAdmin)

enter image description here

But instead of one checkbox with "N" options, I want "N" textboxes to choose the books.

2 Answers 2

3

You got your cardinalities the wrong way round. As you wrote it, the relationship is "An author has one book, a book has many authors", while you obviously wanted "A book has one author, an author has many books" - or possibly "a book as one or many authors, an author has one or many books".

In the first case, you have to remove the ForeignKey in Author and add a ForeignKey to Book in Author - and use an AdminInline in Author if you want to be able to add books to an author from the AuthorAdmin.

In the second case, you want a ManyToManyField, which can be in either Book or Author...

Sign up to request clarification or add additional context in comments.

Comments

1

You need to use ManyToMany field for books:

books = models.ManyToManyField(Book)

Django doc for ManyToMany.

1 Comment

A ManyToManyField implies that a Book can have more than one author. While it makes sense wrt/ "real world", it's not necessarily the appropriate domain model for the OP's application.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.