V
V
Vasily Vorobyov2016-01-13 10:35:49
Django
Vasily Vorobyov, 2016-01-13 10:35:49

Why doesn't get_object() work in SingleObjectMixin?

Django 1.9
view:

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

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

        if obj.is_legal():
            if not obj.organization.owners.filter(user=self.request.user).exists():
                raise Http404
        else:
            if obj.citizen.user != self.request.user:
                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)

For some reason throws AttributeError: 'SendTransfer' object has no attribute 'object'
Debug shows that get_object is not called at all

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Voronkov, 2016-01-28
@DmitryVoronkov

...
    def form_valid(self, form):
        data = form.cleaned_data
        MoneyTransfer.objects.create(sender=self.get_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)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question