我正在尝试创建一个表单,该表单将根据模型项显示复选框列表。然后还可以根据需要过滤此列表。
但是我收到以下错误并且不确定为什么?
错误:
File "/usr/local/lib/python3.6/site-packages/django/forms/forms.py" in errors
174. if self._errors is None:
Exception Type: AttributeError at /sites/site/auto_gen_subnets/7
Exception Value: 'AutoSubnetForm' object has no attribute '_errors'
forms.py
class AutoSubnetForm(forms.Form):
subnet_type_data = SiteTypes.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:
subnet_type_data = SiteTypes.objects.filter(site_type=self.site_type)
# create list for types
subnet_types = []
for stype in subnet_type_data:
# add tuple for each type
subnet_types.append((stype.id,stype.site_type))
subnets = forms.ChoiceField(
choices=subnet_types,
widget = forms.Select(
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,
'subnet_form': form,
'SiteName' : site_data.location,
'SiteID' : site_id,
}
)
答案 0 :(得分:4)
您覆盖 init 方法。所以你应该把它归还给你的超类。
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:
subnet_type_data = SiteTypes.objects.filter(site_type=self.site_type)
super(AutoSubnetForm, self).__init__(*args, **kwargs)
您没有退回_errors
。因此除了您在覆盖时提供的数据之外,它不知道任何其他数据。如果你想要的话,你应该把它归还给超类。这应该导致它。上面的代码应该修复它。