使用具有基于类的视图的多个ModelForms

时间:2013-05-07 15:10:48

标签: django django-class-based-views class-based-views

我有一种情况,我想在我的CreateView中添加一个额外的模型。我们有一个入门订单系统 允许某人添加订单然后将项目添加到该订单。通常,当有人为第一个订单添加订单时 他们还希望将时间项添加到该订单中,因此我希望将这些模型组合成一个表单并进行处理 在初始订单输入。当表单无法验证时,我遇到了问题。

我已经覆盖了get_context_data以将项目表单添加到模板中,并且我已经重写了post来处理额外的表单。但 当表单无效时,我需要重新渲染传递POST数据的原始表单。什么是覆盖的首选方式 get_context_data是为了使用/不使用POST数据来呈现表单?我应该这样做吗?

def get_context_data(self, **kwargs):
    context = super(OrderAdd, self).get_context_data(**kwargs)
    if self.request.method == 'POST':
        item_form = ItemForm(self.request.POST, prefix='item')
    else:
        item_form = ItemForm(prefix='item')
    context['item_form'] = item_form
    return context

这是我的CreateView的当前形式,我目前卡住了。

class OrderAdd(CreateView):
    model = Order
    form_class = OrderForm
    context_object_name = 'object'
    template_name = 'form.html'

    def get_context_data(self, **kwargs):
        context = super(OrderAdd, self).get_context_data(**kwargs)
        item_form = ItemForm(prefix='item')
        context['item_form'] = item_form
        return context

    def post(self, request, *args, **kwargs):
        order_form = OrderForm(request.POST)
        item_form = ItemForm(request.POST, prefix='item')

        if order_form.is_valid() and item_form.is_valid():
            return self.form_valid(order_form)
        else:
            context = self.get_context_data()
            return render(self.request, 'form.html', context)

1 个答案:

答案 0 :(得分:3)

一种略显不雅的方法:

def get_context_data(self, **kwargs):
    context = super(OrderAdd, self).get_context_data(**kwargs)
    if self.request.method == 'POST':
        return context
    else:
        item_form = ItemForm(prefix='item')
        context['item_form'] = item_form
        return context

def post(self, request, *args, **kwargs):
    order_form = OrderForm(request.POST)
    item_form = ItemForm(request.POST, prefix='item')

    if order_form.is_valid() and item_form.is_valid():
        return self.form_valid(order_form)
    else:
        context = self.get_context_data()
        context['item_form'] = item_form
        return render(self.request, 'form.html', context)

另一种选择:

def get_context_data(self, **kwargs):
    context = super(OrderAdd, self).get_context_data(**kwargs)
    if self.request.method == 'POST':
        item_form = ItemForm(self.request.POST, prefix='item')
    else:
        item_form = ItemForm(prefix='item')
    context['item_form'] = item_form
    return context

def post(self, request, *args, **kwargs):
    order_form = OrderForm(request.POST)
    context = self.get_context_data()
    item_form = context['item_form']

    if order_form.is_valid() and item_form.is_valid():
        return self.form_valid(order_form)
    else:
        return render(self.request, 'form.html', context)