How to add fields dynamically in Django?

1

I'd like to add fields dynamically in DjangoAdmin.

Models.py file:

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

admin.py file:

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

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

How the graphical interface is currently:

Iwouldliketodynamicallyaddseveralbookstoacertainauthor.

Insteadofhavingacheckboxwith"N" options, I would like to have "N" selectboxes, as many as needed.

Something like this:

Itriedusing Inline , but I just I could add a new book, not select the ones that already exist.

What is the most elegant way to do this?

    
asked by anonymous 13.01.2016 / 18:57

1 answer

1

I believe django's filter_horizontal will solve your problem.

In your admin.py class, put the tag to indicate this.

class BookAdmin(admin.ModelAdmin):
    filter_horizontal = ('author',)

admin.site.register(Book)

You will have a select multiple equal to the permission with the option to add a new element.

    
14.01.2016 / 19:40