[Fixed]-How to use two different models in CreateView in django

1👍

CBVs are designed for code reuse. If you don’t yet have another class that could benefit of code you posted, the actual amount of code is almost identical, be that a CBVs or a plain function.

But the more pythonic and Django-ish (from my biased POV) way would be to:

  1. Inherit your class from the FormView instead of the View. That eases the form management a bit.
  2. Add a SingleObjectMixin to get the object from url kwargs for free.
  3. Move your object validation to the get_object() method. It’s a good practive to raise 404 if your object doesn’t validate.
  4. Refactor out the get_context_data() as you already have all that data in your context (request, form and object)
  5. Instead of relying on the self.request.POST, clean your data through the form.

    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).dispatch(request, *args, **kwargs)
    
        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)
    

Some of your code has gone thanks to the CBV magic, some just has moved to another methods. Take a look, I’d welcome your comments.

Leave a comment