Django Forms - 动态选择字段过滤

时间:2018-02-06 14:31:36

标签: python django

我正在尝试动态过滤表单中显示的选项。表单字段是从模型生成的。目前正在显示所有选项而不应用任何过滤器。

在视图中我得到了current_type然后将其传递给表单,以过滤同样具有相同site_type的子网,或者这是应该发生的事情。

任何人都可以看到为什么过滤器不适用?

forms.py

class AutoSubnetForm(forms.Form):
    subnet_type_data = SubnetTypes.objects.all()

    def __init__(self, *args, **kwargs): 
        self.site_type = kwargs.pop("site_type")
        # get site type if set and filter against it
        if self.site_type:
            self.subnet_type_data = SubnetTypes.objects.filter(related_sites=self.site_type)

        super(AutoSubnetForm, self).__init__(*args, **kwargs)

    # create list for types
    subnet_types = []
    for stype in subnet_type_data:
        # add tuple for each type
        subnet_types.append((stype.id,stype.subnet_type))

    subnets = forms.MultipleChoiceField(
            choices=subnet_types,
            widget = forms.CheckboxSelectMultiple(
            attrs = {'class': 'form-control'}
        )
    )

views.py

@login_required
@user_passes_test(lambda u: u.has_perm('config.add_subnet'))  
def auto_gen_subnets(request, site_id):
    #generate_subnets(site_id)
    from config.models import SubnetTypes   
    site_data = get_object_or_404(SiteData.objects.select_related('site_type'),pk=site_id)
    subnets = None
    if request.method == 'GET':
        form = AutoSubnetForm(site_type=site_data.site_type)
    else:
        # A POST request: Handle Form Upload
        form = AutoSubnetForm(request.POST)
        # If data is valid, proceeds to create a new post and redirect the user
        if form.is_valid():
            subnets = form.cleaned_data['subnets']

    return render(request, 'sites/generate_subnets.html', {
        'data': subnets,
        'form': form,  
        'SiteName' : site_data.location,
        'SiteID' : site_id, 
        }
    )

1 个答案:

答案 0 :(得分:2)

如果您要从模型生成表单,则需要ModelMultipleChoiceField

尝试这样的事情:

class AutoSubnetForm(forms.Form):

    def __init__(self, *args, **kwargs): 
        site_type = kwargs.pop("site_type")

        queryset = SubnetTypes.objects.all()
        if site_type:
            queryset = queryset.filter(related_sites=site_type)

        super(AutoSubnetForm, self).__init__(*args, **kwargs)

        self.fields['the_name_of_your_form_field'] = forms.ModelMultipleChoiceField(
            queryset=queryset,
            widget = forms.CheckboxSelectMultiple(
                attrs = {'class': 'form-control'}
            )
        )