【发布时间】:2018-07-16 15:44:52
【问题描述】:
我正在尝试动态过滤表单中显示的选项。表单字段是从模型生成的。目前,所有选择都在显示,没有应用任何过滤器。
在视图中,我获取当前的 site_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,
}
)
【问题讨论】: