2016-01-13 44 views
0

還有就是我的觀點:爲什麼在FormView後不會調用postView後清理?

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是有效的。問題是什麼?

+0

問題編輯。無論如何,form_invalid都在調用。 form.clean()沒有調用 –

回答

2

您已覆蓋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 
相關問題