【问题标题】:django: how to display list of checkboxes for one-to-many relationship?django:如何显示一对多关系的复选框列表?
【发布时间】:2023-03-03 03:29:01
【问题描述】:

假设Blog 模型与Entry 模型具有一对多的关系。在表单中,是否有一种优雅的方式将博客实例的条目集显示为复选框列表,以便用户可以选择和处理部分/全部条目?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    当然。

    class BlogForm(forms.ModelForm):
        entries = forms.ModelMultipleChoiceField(
            queryset=Entry.objects.all(),
            widget=forms.CheckboxSelectMultiple)
    
        class Meta:
            model = Blog
    
        def __init__(self, *args, **kwargs):
            super(BlogForm, self).__init__(*args, **kwargs)
            if self.instance:
                entries = Entry.objects.filter(blog=blog)
                self.fields['entries'].queryset = entries
    

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      相关资源
      最近更新 更多