Django:FormView,get_context_data使表单验证无效并丢弃输入

2024-10-03 04:36:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让我的FormView进行验证(显示哪些字段包含错误),并在表单无效时重新使用已经输入的内容

目前,如果表格无效:

  1. 表单/表单字段上未显示错误(红色矩形环绕,错误文本如下)
  2. 表单被重新加载,并且所做的输入被丢弃(表单作为新的重新加载)

似乎get_context_data使基于类的FormView的默认行为无效

如何在一个上下文中验证多个表单,以及如何在这样的上下文中重新加载已尝试的表单数据

class ProductFormView(FormView):
    template_name = 'product/product_create.html'
    model = Product
    success_message = f'Product created successfully'
    success_url = '/product/list'

    def get_context_data(self, **kwargs):
        context = super(ProductFormView, self).get_context_data(**kwargs)
        context['form_1'] = CommonFieldsForm(instance=self.model())
        context['form_2'] = PriceForm(instance=self.model())
        return context

    def form_invalid(self, form):
        response = super().form_invalid(form)
        return response

    def form_valid(self, form):
        response = super().form_valid(form)
        return response

Tags: selfform表单datagetmodelreturnresponse