Django表单和formset - 检查是否有用户,如果没有则引发错误

时间:2014-01-07 13:47:29

标签: django forms validation

我有一个应用程序,其中有一个表单,您可以在其中按名称或formset指定用户,您可以在其中选择用户组或两者。

我需要添加某种验证,当手动和/或从组中选择的用户总数等于0时,表单将不会继续。

如何在表单和formset之间进行通信以引发验证错误? 是否存在另一种引发错误的方式,如典型的形式和formset?

def form_valid(self, form):
    context = self.get_context_data()
    formset = context.get('formset')

    is_valid = form.is_valid()

    if formset:
        is_valid &= formset.is_valid()

    if not is_valid:
        context['form'] = form

        return self.render_to_response(context)

    task = form.save()

    if self.has_formset():
        added_groups_list = []
        for formset_form in formset:
            ...do something...




class TaskForm(forms.ModelForm):
sms_preview = forms.CharField(
    label=u"Treść wiadomości SMS", required=False, widget=forms.Textarea(attrs={
        'cols': 2,
        'rows': 2,
        'readonly': 'readonly',
    })
)

users = forms.ModelMultipleChoiceField(User.objects.none(), label=u'Użytkownicy', required=False)

class Meta:
    model = Task
    fields = ('procedure', 'priority', 'location', 'message', 'date_from', 'date_to',
              'users')
    widgets = {
        'date_from': DateTimePickerInput,
        'date_to': DateTimePickerInput,
        'procedure': forms.Select(attrs={'class': 'chosen',
                                         "data-placeholder": u"Wybierz procedurę",
                                         }),
        'message': forms.Textarea(attrs={'cols': 2, 'rows': 2,
                                         'placeholder': u"Własna treść wiadomości (opcjonalnie)"
                                         }),
        'hours': forms.TextInput(attrs={'placeholder': u'Godziny'}),
        'minutes': forms.TextInput(attrs={'placeholder': u'Minuty'}),
    }

def __init__(self, *args, **kwargs):
    self.site = kwargs.pop('site')
    self.procedure = kwargs.pop('procedure', None)
    self.user = kwargs.pop('user', None)

    super(TaskForm, self).__init__(*args, **kwargs)

    self.helper = FormHelper()

    layout = Layout('procedure')

    date_from = timezone.now() + timezone.timedelta(hours=1)
    self.fields['date_from'].initial = date_from.strftime("%d.%m.%Y %H:%M")

    date_to = date_from + timezone.timedelta(hours=1)
    self.fields['date_to'].initial = date_to.strftime("%d.%m.%Y %H:%M")

    self.fields['date_from'].required = True
    self.fields['date_to'].required = True
    self.fields['message'].label = ""
    self.fields['users'].widget.attrs = {
        'class': 'chosen',
        'data-placeholder': u'Nie wybrano użytkowników.',
        'readonly': 'readonly',
        'disabled': 'disabled',
    }





class TaskActionGroupFormset(forms.formsets.BaseFormSet):
    def __init__(self, *args, **kwargs):
        self.site = kwargs.pop('site')
        self.procedure = kwargs.pop('procedure', None)
        super(TaskActionGroupFormset, self).__init__(*args, **kwargs)

    @cached_property
    def forms(self):
        return [self._construct_form(i, site=self.site, procedure=self.procedure)
                for i in xrange(self.total_form_count())]

    @property
    def empty_form(self):
        form = self.form(
            auto_id=self.auto_id,
            prefix=self.add_prefix('__prefix__'),
            empty_permitted=True,
            site=self.site,
        )
        self.add_fields(form, None)
        return form

1 个答案:

答案 0 :(得分:0)

由于您使用的是Django表单,因此您需要使用clean() method并覆盖它以运行验证。