How to add fields dynamically in Django?

Asked

Viewed 491 times

1

I would like to add fields dynamically in Djangoadmin.

File 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

Admin file.py:

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:

enter image description here

I would like to dynamically add several books to a particular author.

Instead of having a checkbox with "N" options, I would like to have "N" selectboxes, as many as needed.

Something like this:

enter image description here

I tried to use Inline, but I could only add a new book, not select the ones that already exist.

What’s the most elegant way to do this?

1 answer

1

I believe that the filter_horizontal Django 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.