【问题标题】:django: pass formset data into another viewdjango:将表单集数据传递到另一个视图
【发布时间】:2020-10-29 11:16:56
【问题描述】:

我的问题建立在这篇文章How to pass data between django views 之上。我正在尝试做类似的事情,即将视图 1 中输入的数据用于视图 2。

然而,挑战在于使用表单集,我需要访问多行数据输入,而不仅仅是值。我不知道如何实现这一点

这是我目前所拥有的: 视图 1:

def New_Sales(request):
    #context = {}
    form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount', 'customer_name'))
    
    
    if request.method == 'GET':
        formset = form(queryset= historical_recent_data.objects.none())
        #blank_form = formset.empty_form
    elif request.method == 'POST':
        formset = form(request.POST)
        #blank_form = formset.empty_form
        if formset.is_valid():
            request.session['sale'] = request.POST['sale']  
            
            
            
            
            
            for check_form in formset:
                check_form.save()
            
                quantity = check_form.cleaned_data.get('Quantity')
                id = check_form.cleaned_data.get('Id')
                update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity)
                update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity)
                
            
            
        
            return redirect('/dash22.html') 
    
  
    
    return render(request, 'new_sale.html', {'formset':formset})

并查看 2:

def invoice_view(request):
    request = request.session.get('sale'))

#... i need to get each row of the formset from the above view

#and  I am stuck!!

我希望有人能提供解决方案,我在 django doc 中找不到任何关于此的内容。

【问题讨论】:

    标签: python django


    【解决方案1】:

    好吧,我不知道我是否理解你的问题,但我会尽力回答你。 你可以用 2 种不同的方式来做到这一点。一种是在前端发送带有帖子的值(HTML 表单或 AJAX POST)。如果您想从后端执行此操作,您可以向方法添加更多参数并传递值(或整个表单集),例如:

    def invoice_view(request, val1=None, val2=None):
        print(val1)
        request = request.session.get('sale'))
    

    然后你可以从另一个视图调用它,就像一个普通的函数:

    invoice_view(request, "asd", "asd2")
    

    【讨论】:

    • 我知道你在做什么,但是我是个菜鸟,我不知道如何将多行的表单参数作为函数参数传递
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    相关资源
    最近更新 更多