Search code examples
djangodjango-formsdjango-viewschained-select

How to do Django Chained Select In Forms.py?


class Library(forms.ModelForm):

    author = forms.ChoiceField(
        widget = forms.Select(),
        choices = ([
            ('Jk Rowling','Jk Rowling'), 
            ('agatha christie','agatha christie'),
            ('mark twain','mark twain'), 
        ]),
        initial = '1', 
        required = True,
    )
    books = forms.ChoiceField(
        widget = forms.Select(), 
        choices = ([
            ('Harry Potter 1','Harry Potter 1'),  # 1
            ('Harry Potter 2','Harry Potter 2'),  # 2
            ('Harry Potter 3','Harry Potter 3'),  # 3
            ('Harry Potter 4','Harry Potter 4'),  # 4
            ('The A.B.C. Murders','The A.B.C. Murders'),  # 5
            ('Dumb Witness','Dumb Witness'),  # 6
            ('Death on the Nile','Death on the Nile'),  # 7
            ('Murder Is Easy','Murder Is Easy'),  # 8
            ('Roughing It','Roughing It'),  # 9
            (' The Gilded Age ',' The Gilded Age '),  # 10
            ('Adventures of Tom Sawyer','Adventures of Tom Sawyer'),  # 11
        ]),
        initial = '1',
        required = True,
    )

If User Select the Author As Jk Rowling the harry potter series must be populated in the books choice field (1 to 4 choices)

If User select the Author As Agatha Christie Then only the (5 to 8 )must be populated in the books choice field

If User select the Author As Mark Twain Then only the ( 8 to 11 ) choice must be populated in the select widget of the books choice field

I want to filter the choices can anyone help ?


Solution

  • 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.