为什么在发布后不在FormView中调用clean?

时间:2016-01-13 11:49:32

标签: django django-class-based-views

有我的观点:

class SendTransfer(SingleObjectMixin, FormView):
    model = BankAccount
    form_class = SendTransferForm
    template_name = 'dashboard/send_transfer.html'

    def dispatch(self, request, *args, **kwargs):
        self.object = self.get_object()
        return super(SendTransfer, self).dispatch(request, *args, **kwargs)

    def get_object(self, queryset=None):
        obj = super(SendTransfer, self).get_object(queryset)

        if not obj.is_owner(self.request.user.citizen):
            raise Http404

        return obj

    def form_valid(self, form):
        data = form.cleaned_data
        MoneyTransfer.objects.create(sender=self.object,
                                     receiver=data['receiver'],  # ModelChoiceField in the form
                                     total=data['total'],  # FloatField in the form, etc.
                                     when=timezone.localtime(timezone.now()),
                                     comment=data['comment'])
        return redirect('AccountDetail', self.object.pk)

    def form_invalid(self, form):
        return render(self.request, self.template_name, self.get_context_data())

    def get_form_kwargs(self):
        return {'sender': BankAccount.objects.get(id=self.kwargs['pk']), 'user': self.request.user}

表单提交时 - 我得到的结果与获取后相同。调试器说没有调用clean()但是form_invalid有效。有什么问题?

1 个答案:

答案 0 :(得分:3)

您已覆盖get_form_kwargs,现在您不再将data传递给表单。没有data,表单是未绑定的,因此永远无效。

最好首先调用super(),更新kwargs,然后返回它们。

def get_form_kwargs(self):
    kwargs = super(SendTransfer, self).get_form_kwargs()
    kwargs['sender'] = BankAccount.objects.get(id=self.kwargs['pk']), 
    kwargs['user'] = self.request.user
    return kwargs