首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Forms.py中进行链式选择?

如何在Forms.py中进行链式选择?
EN

Stack Overflow用户
提问于 2016-05-16 05:24:49
回答 1查看 6K关注 0票数 3
代码语言:javascript
复制
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项选择)。

如果用户选择作者为Agatha Christie,则必须在“图书选择”字段中填充(5至8)

如果用户选择作者为Mark,则必须在图书选择字段的select小部件中填充(8至11 )选项

我想过滤那些选择谁能帮上忙吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-16 07:59:59

authorbooks保存在DB中。

models.py

代码语言:javascript
复制
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

代码语言:javascript
复制
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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37247207

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档