2016-05-16 41 views
2
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, 
    ) 

如果用戶選擇了作者作爲JK羅琳的哈利·波特系列必須在書籍的選擇字段來填充(1至4選擇)如何做Django鏈接在Forms.py中選擇?

如果用戶選擇了作者作爲阿加莎·克里斯蒂那麼只有(5〜8 )必須在書籍的選擇現場

填充如果用戶選擇作者正如馬克吐溫然後只(8〜11)選擇必須在書籍的選擇字段的選擇控件來填充

我想過濾這些選擇可以幫助嗎?

+1

[如何在使用Modelform和jquery的django中獲得互相依賴的下拉列表?](http://stackoverflow.com/questions/14121132/how-to-get-interdependent-dropdowns-in-django-using-modelform - 和 - jquery) – e4c5

回答

3

保留authorbooks在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 

基於Author選擇,觸發從AJAX調用,並得到所有相應books

+0

謝謝Anoop! –