Django访问FormSet数据并放入pandas Dataframe

时间:2018-06-07 01:46:31

标签: python django pandas formset

我正在尝试生成看起来像这样的formset。 formset output needed然后访问formset数据,将其放入pandas数据帧进行计算,以便在另一个python .py文件中访问。但是,一旦我测试它,我的代码就不会向我提取任何用户输入。请告知应该采取什么措施来解决它?

views.py

   from django.shortcuts import render
   from django.http import HttpResponse
   from django.http import HttpResponseRedirect
   from django.shortcuts import render
   from .forms import AssumptionsForm, AssumptionsFormSet
   from django.forms import formset_factory

    data_list = []        

    def index(request):
        return HttpResponse("Hello, client. You're at the inputs page.")

    def get_assumptions(request):    

        if request.method == 'POST':

            formset = AssumptionsFormSet(request.POST)

            if formset.is_valid():
                for f in formset:
                    cd = f.cleaned_data
                    data1 = cd.get('bad')
                    data2 = cd.get('likely')
                    data3 = cd.get('best')
                    data_list.append(data1)
                    data_list.append(data2)
                    data_list.append(data3)
        else:
            formset = AssumptionsFormSet()

        return render(request, 'assumptions.html', {'formset': formset})

assumptions.html

    <form action="/analysis2/" method="post">
    {% csrf_token %}
    <table>
    {% for form in formset %}
        {{ form }}
    {% endfor %}
    </table>
    <input type="submit" value="Submit" />
    </form>

forms.py

from django import forms
from django.forms import formset_factory

class AssumptionsForm(forms.Form):
    #title = forms.CharField()
    bad = forms.FloatField()
    likely = forms.FloatField()
    best = forms.FloatField()

AssumptionsFormSet = formset_factory(AssumptionsForm, extra = 5)

1 个答案:

答案 0 :(得分:1)

如文档中所述,为了在视图中使用formset,您需要在表单中包含formset.management_form。以下是文档中的示例:

<form method="post">
    {{ formset.management_form }}
    <table>
        {% for form in formset %}
        {{ form }}
        {% endfor %}
    </table>
</form>

以下是如何使用formset的一个很好的示例: https://medium.com/@adandan01/django-inline-formsets-example-mybook-420cc4b6225d pandas部分与您在上一篇文章from Django forms to pandas DataFrame

中发布的内容相同