[Django]-How to do Django Chained Select In Forms.py?

6👍

Keep author and books in DB.

models.py

Class Author(models.Model):
    name = models.CharField(max_length=50)
    ......

class Books(models.Model):
    ....
    author = models.ForeignField(Author)
    ....

Class Library(models.Model):
    .....
    author = models.ForeignKey(Author)
    books = models.ForeignKey(Books)
    .....

forms.py

class Library(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(Library, self).__init__(*args, **kwargs)
        self.fields['author'].choices = list(Author.objects.values_list('id', 'name'))

        self.fields['books'].choices = list(Books.objects.values_list('id', 'name'))


    class Meta:
        Model: Library

Based on Author selection, trigger from ajax call and get all the corresponding books.

👤Anoop

Leave a comment