Django - 将模型表格集数据保存到CBV中的会话

时间:2017-11-28 14:47:24

标签: python django forms django-generic-views

目标:我正在尝试将modelformset数据保存到会话中。我有一个视图,其中需要为从先前视图中的复选框中选择的项目填写相同的表单字段集。

问题:我的modelformset以某种方式仅返回cleaning_data之后的最后一组输入(但我可以看到request.POST中的所有输入)。

我没有得到验证或任何类型的错误(如果我切换输入,之前传递的输入不通过cleaning_data)

request.POST

<QueryDict: {'form-TOTAL_FORMS': ['1'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'csrfmiddlewaretoken': ['#abbr', '#abbr', '#abbr'], 'form-0-pd_month': ['8', '5', '7'], 'form-0-pd_day': ['28', '28', '28'], 'form-0-pd_year': ['2017', '2017', '2017'], 'form-0-var': ['t1', 't2', 't3'], 'form-0-id': ['', '', '']}>

cleaned_data

{'pd': datetime.date(2017, 7, 28), 'var': 't3', 'id': None}

我检查了

以及Django doc,但这些都不适合我。

代码:我尽可能少地粘贴代码而不会影响大局。

views.py

#checklist view
class VView(CreateView):
    form_class = VForm
    template_name = 'b/ve.html'

    def post(self, request):
        form = VForm(request.POST)
        if form.is_valid():
            val = form.cleaned_data['ve']
            name = []
            for obj in val:
                temp = dict(V.LIB).get(obj)
                name.append(temp)

            request.session['val'] = val
            request.session['name'] = name
            return HttpResponseRedirect('/b/d/')


#fill in same fields for each selection in VView
class DView(CreateView):
    template_name = 'b/d.html'

    def get(self, request):
        name = request.session['name']
        formset = VarDFormSet()
        return render(request, self.template_name, {'name': name, 'formset': formset})

    def post(self, request):
        formset = VarDFormSet(request.POST)
        if formset.is_valid():
            for form in formset:
                var = form.cleaned_data['var']
                pd = form.cleaned_data['pd']
                pd = pd.strftime('%Y-%m-%d')

            request.session['var'] = var
            request.session['pd'] = pd
            return HttpResponseRedirect('/b/loc/')

models.py

class V(models.Model):
    LIB = [
        #list of lists
        ]
    checklist = models.CharField(max_length = 50, choices = LIB)

class Setup(models.Model):
    ve = models.ManyToManyField(V)
    var = models.CharField(max_length = 20, null = True)
    pd = models.DateField(null = True)

forms.py

class VForm(ModelForm):
    class Meta:
        model = Setup
        fields = ['ve']


class VarDForm(ModelForm):
    #set initial value for pd

    class Meta:
        model = Setup
        fields = ['pd', 'var']

VarDFormSet = modelformset_factory(Setup, fields=('pd', 'var'), form=VarDForm)

DView模板

<form method='post' action=''>
{{ formset.management_form }}

    {% for form in formset  %}
        {% for obj in name %}

        <h2> {{obj}} </h2>
            {% csrf_token %}
            {{ form }}

        {% endfor %}        
    {% endfor %}

<input type='submit' value='次へ'/>
</form>

1 个答案:

答案 0 :(得分:0)

这不是关于formsets的问题。您有多个值,并迭代它们,但在每次迭代中,您将值分配给相同的局部变量。因此,每次迭代都会覆盖每个变量,只留下最后一个值。

目前尚不清楚您要做什么,但为什么不能简单地将formset.cleaned_data的值分配给会话中的元素?