我正在尝试为我的Django表单添加验证。
我想要为我的inlineformset至少要一个子模型。
我使用以下作为参考: Inline Form Validation in Django
我仍然收到错误
第454行,在formset_factory中 返回类型(表单。名称 + str(' FormSet'),(formset,),attrs)TypeError:元类冲突:派生类的元类必须 是所有基础的元类的(非严格的)子类
from django.forms import inlineformset_factory
from .models import *
from django.forms.models import BaseInlineFormSet
from django import forms
class PropertyForm(forms.ModelForm):
class Meta:
model = Property
exclude = ()
class UnitForm(forms.ModelForm):
class Meta:
model = Unit
exclude = ()
class CustomUnitFormset(BaseInlineFormSet):
def is_valid(self):
return super(CustomUnitFormset, self).is_valid() and \
not any([bool(e) for e in self.errors])
def clean(self):
# get forms that actually have valid data
count = 0
for form in self.forms:
try:
if form.cleaned_data and not form.cleaned_data.get('DELETE', False):
count += 1
except AttributeError:
pass
if count < 1:
raise forms.ValidationError('You must have at least one unit')
UnitFormSet = inlineformset_factory(Property, Unit, form=PropertyForm,
formset='CustomUnitFormset',
extra=0,
min_num=1,
validate_min=True,
validate_max=True,
max_num=10,
)
view.py
class PropertyUnitCreate(LoginRequiredMixin, CreateView):
model = Property
fields = ['address']
success_url = reverse_lazy('property-list')
def get_context_data(self, **kwargs):
data = super(PropertyUnitCreate, self).get_context_data(**kwargs)
if self.request.POST:
data['units'] = UnitFormSet(self.request.POST)
else:
data['units'] = UnitFormSet()
return data
def form_valid(self, form):
context = self.get_context_data()
units = context['units']
form.instance.user = self.request.user
with transaction.atomic():
self.object = form.save()
if units.is_valid():
units.instance = self.object
units.save()
return super(PropertyUnitCreate, self).form_valid(form)
我也尝试了解这里解释的继承问题:Triple inheritance causes metaclass conflict... Sometimes
我的观点逻辑来自https://medium.com/@adandan01/django-inline-formsets-example-mybook-420cc4b6225d
但我不知道我从哪个类继承了两个会导致此错误的类。如果我删除&#34;表单集=&#39; CustomUnitFormset&#39 ;, &#34;
有人可以解释错误的原因以及我如何防止这种情况?我可以更好地管理我的forms.py文件吗?
答案 0 :(得分:0)
您需要将实际的formset类(而不是字符串)传递给工厂。
UnitFormSet = inlineformset_factory(Property, Unit, form=PropertyForm,
formset=CustomUnitFormset, ...)