Setting up and processing 2 modelforms with the same FormView class

I am trying to use a single FormView class to render and process two related but different ModelForms. One of the forms has FileInput as one of its fields and it is not submitting properly when I click the respective button.

views.py

class MyView(LoginRequiredMixin, FormView):
    template_name = "tmp.html"
    http_method_names = ["get", "post"]
    login_url = "/to/login"
    form_class = AForm
    success_url = reverse_lazy("profile")

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        prf = ModelA.objects.get(id=self.request.user.id)
        context["form_a"] = AForm(instance=prf)
        context["form_b"] = BForm(instance=None)
        return context


    def post(self, request, *args, **kwargs):
        if "submit_a" in request.POST:
            self.form_class = AForm
        if "submit_b" in request.POST:
            self.form_class = BForm
        return super().post(request, *args, **kwargs)


    def form_valid(self, form):
        if self.form_class == AForm:
            form.save()
        elif self.form_class == BForm:
            form.save()
        return super().form_valid(form)

The related forms.py for ModelA looks something like this:

class AForm(ModelForm):
    img_field = ImageField(widget=FileInput)

Two issues I'm currently having:

When the form loads and the user clicks the submit button with previous data, I'm getting <ul class="errorlist"><li>img_field<ul class="errorlist"><li>This field is required.</li></ul></li></ul> when I check form.errors.

When the user selects an image to upload and clicks submit (submit_a), I'm getting IntegrityError on the id (user id) column which is returning null. I assume that since I am sending a specific user instance to the form context via

prf = ModelA.objects.get(id=self.request.user.id)
context["form_a"] = AForm(instance=prf)

the related user data (including the img_field data) used for constructing the form will be available when the form is submitted.

What are my options to solve these issues?

Back to Top