Using Multiple ModelForms with Class-Based Views

萝らか妹 提交于 2019-12-06 20:26:24

One slightly inelegant approach:

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)

Another alternative:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!