gpt4 book ai didi

python - Django - 表单对象没有属性 '_errors'

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:00 26 4
gpt4 key购买 nike

我正在尝试创建一个表单,该表单将显示基于模型项目的复选框列表。如果需要,还可以过滤此列表。

但是我收到以下错误并且不确定原因是什么?

错误:

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'

表单.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,
}
)

最佳答案

您覆盖了 init 方法。所以你应该把它返回给你的父类(super class)。

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。因此,除了您在覆盖时提供的数据外,它不知道任何其他数据。如果你想要所有的东西,你应该把它归还给superclass。那应该导致它。上面的代码应该可以修复它。

关于python - Django - 表单对象没有属性 '_errors',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48641121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com