无法在django formset中获取表单值

时间:2014-10-29 20:51:20

标签: django django-models django-forms

我试图在formset中获取特定表单的结果。我尝试过没有成功的formset和modelformset。

使用FormSet

我的观点如下:

def display(request, pk=None, action='add'):
    customer = get_customer(request)        
    qs = CustomerActivity.objects.filter(customer=customer)


    AuthorFormSet = modelformset_factory(CustomerActivity, form=ActivityEntryForm, extra=0)
    if request.method == 'POST':
        formset = AuthorFormSet(request.POST)

        if form.is_valid:
            print 'form valied'
            for form in formset:
                 print form.cleaned_data['duration']
            duration = request.POST.get('duration')
            activity = request.POST.get('activity')

            print duration


    else:
        formset = AuthorFormSet(queryset=qs)

    context = {
        'formset':formset,
    }
    return render(request, 'activity/activity.html', context)

我收到错误:

CustomerActivityForm' object has no attribute 'duration'

我甚至没有名为CustomerActivityForm的表单,它名为ActivityEntryForm:

class ActivityEntryForm(forms.ModelForm):

    duration = forms.IntegerField(required=False)

    class Meta:
        model = CustomerActivity
        fields = ('duration',)

我的常规拼版尝试

以下是我的观点:

def display_2(request, pk=None, action='add'):
    customer = get_customer(request)
    entered_at, day_start, day_end = get_date_query_elements(request)


    qs = CustomerActivity.objects.filter(customer=customer).values()

    ArticleFormSet = formset_factory(ActivityEntryForm, extra=0)
    if request.method == 'POST':


        formset = ArticleFormSet(request.POST, request.FILES)
        if formset.is_valid():
            for form in formset:
                print form.duration
            pass
    else:
        formset = ArticleFormSet(initial=qs)

    context = {
        'formset':formset,
    }
    return render(request, 'activity/activity.html', context)

以下是表格:

class ActivityEntryForm(forms.Form):
    duration = forms.IntegerField(required=False)

我收到错误:

ActivityEntryForm' object has no attribute 'duration'

如何获得持续时间值???

1 个答案:

答案 0 :(得分:2)

与任何表格一样,经验证的数据位于form.cleaned_data,这是一本字典。

print form.cleaned_data['duration']

文档中对此进行了详细说明。