无法使用def clean()

时间:2019-03-19 13:44:56

标签: python django django-forms

我正在努力弄清楚如何将表单集验证应用于我的表单集。保存表单集时,不会运行def clean方法(即“在表单集验证中”永远不会打印到控制台)。有什么想法吗?

forms.py

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 }}

谢谢!

1 个答案:

答案 0 :(得分:0)

此刻,您导入了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)
    ...