我正在努力弄清楚如何将表单集验证应用于我的表单集。当我保存表单集时,不会运行def clean方法(即,“在表单集验证中”永远不会输出到控制台)。有什么想法吗?
表格
class UserServiceForm (forms.ModelForm):
active = forms.BooleanField(required=False)
sale_expiry = forms.DateField(required=True)
class Meta:
model = UserService
exclude = ('user',)
class UserServiceFormSet(BaseFormSet):
def clean(self):
for form in self.forms:
print('In formset validation')
user_title = form.cleaned_data['user_title']
title = form.instance.title
if user_title == None and title == None:
self.add_error('user_title', "Please enter a title for this service.")
views.py
from accounts.forms import UserServiceForm, UserServiceFormSet
from accounts.models import UserService
def userservices(request):
UserServiceFormSet = modelformset_factory(UserService, form=UserServiceForm)
formset = UserServiceFormSet(request.POST or None, request.FILES or None, queryset=UserService.objects.filter(user=user), prefix='first')
... non-relevant bits of view...
if request.method == 'POST':
if formset.is_valid():
formset_instances = formset.save(commit=True)
模板
我的模板包含
{{ formset.non_form_errors }}
{% csrf_token %}
{{ formset.management_form }}
field level error tags (eg. {{ form.active_service.errors }}
谢谢!
最佳答案
目前,您导入了UserServiceFormSet
,但是随后在不使用它的情况下将其替换。
from accounts.forms import UserServiceForm, UserServiceFormSet
def userservices(request):
UserServiceFormSet = modelformset_factory(UserService, form=UserServiceForm)
...
您需要将表单集传递给
modelformset_factory
。我建议将类重命名为BaseUserServiceFormSet
以避免名称冲突。from accounts.forms import UserServiceForm, BaseUserServiceFormSet
def userservices(request):
UserServiceFormSet = modelformset_factory(UserService, form=UserServiceForm, formset=BaseUserServiceFormSet)
...
关于python - 无法使用def clean()运行表单集验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55242504/