L
L
leviathan2020-06-28 04:31:11
Django
leviathan, 2020-06-28 04:31:11

Using multiple forms in one CBV?

I am currently using this code:

Spoiler

class ProductPage(TemplateView):
    category_form_class = CategoryForm
    product_form_class = ProductForm

    template_name = 'personal_area/pages/products.html'

    def post(self, request):
        post_data = request.POST or None
        profile_id = request.user.id

        category_form = self.category_form_class(post_data, profile_id=profile_id, prefix='category')
        product_form = self.product_form_class(post_data, prefix='product')

        product_form.fields['category'].choices = user_category(request.user.id)

        context = self.get_context_data(
            category_form=category_form,
            product_form=product_form,

            product_list=Product.objects.filter(profile_id=request.user.id),
            category_list=Category.objects.filter(profile_id=request.user.id)
        )

        if category_form.is_valid():
            self.form_save(form=category_form, profile_id=profile_id)
        if product_form.is_valid():
            self.form_save(form=product_form, profile_id=profile_id)

        return self.render_to_response(context)

    @staticmethod
    def form_save(form, profile_id):
        form_commit = form.save(commit=False)
        form_commit.profile_id = profile_id
        form_commit.save()
        return form_commit

    def get(self, request, *args, **kwargs):
        return self.post(request)


He works. However, after submitting one of the forms, form.errors fires on the other form and displays errors "name Required field." and so on for all required fields.
How can you fight it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2020-06-28
@The_Lars

How can you fight it?
do not do this
1. why form_save is made staticmethod, it’s more like you don’t understand why
2. usually one form is one view
3. there is a FormView to work with forms and if you want several, but at one moment you process one form, don’t use form_class, otherwise we override the get_form_class or get_form method

D
Dmitry, 2020-06-28
@pyHammer

leviathan you need to use this https://gist.github.com/badri/4a1be2423ce9353373e1...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question