Y
Y
YuriyCherniy2020-05-31 14:08:27
Django
YuriyCherniy, 2020-05-31 14:08:27

How to validate form data if the form is generated by another View?

Wrote DetailViewwhich, in addition to the main work, generates a form:

class CategoryDetail(LoginRequiredMixin, DetailView):
    model = Category
    raise_exception = True

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['item_list'] = Item.objects.filter(
            category_id=self.kwargs['pk']
        ).exclude(is_archived=True)

        context['form'] = ItemChoiceForm
        return context

under the spoiler screen for clarity:
spoiler
5ed38cf922c07352044711.png

Adds a product to the current View category:
class AddItemToCategory(LoginRequiredMixin, View):
    raise_exception = True

    def post(self, request, **kwargs):
        item = Item.objects.filter(pk=request.POST['item'])
        item.update(category=kwargs['pk'])
        messages.success(request, 'Товар добавлен в категорию')
        return redirect(reverse('category_detail_url', args=[kwargs['pk']]))

As you can see, I'm using raw data from a POST request without any validation pk=request.POST['item']. How in such a situation to check the data arrived from the client?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-05-31
@YuriyCherniy

why not use FormView or UpdateView rather than View?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question