0

由于表单较长,我为它创建了一个 ModelForm 向导,以便用户可以执行第 1 步和第 2 步。实现后,表单数据不会保存在数据库中。以下是我的代码。

楷模

class FimpForm1(ModelForm):
    class Meta:
        model=Fimp
        fields=('who_are_you','name','main_view','side_view','other_1_view','other_2_view','other_3_view','other_4_view','other_5_view','other_6_view','other_7_view','other_8_view')



class FimpForm2(forms.ModelForm):
     details=forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
    class Meta:
       model=Fimp
       fields=('address','city','state','email','phone_no','details','price')
       exclude=('user','pub_date','slug')

视图.py

class FimpWizard(SessionWizardView):
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'photos'))
    def done(self, form_list, **kwargs):
        form=FimpForm1 and FimpForm2(self.request.POST,self.request.FILES)
        if form.is_valid():
            data=form.cleaned_data
            newfimp=Fimp(
                user=request.user,
                pub_date=datetime.datetime.now(),
                who_are_you=data['who_are_you'],
                name=data['name'],
                main_view=request.FILES.get('main_view'),
                side_view=request.FILES.get('side_view'),
                other_1_view=request.FILES.get('other_1_view'),
                other_2_view=request.FILES.get('other_2_view'),
                other_3_view=request.FILES.get('other_3_view'),
                other_4_view=request.FILES.get('other_4_view'),
                other_5_view=request.FILES.get('other_5_view'),
                other_6_view=request.FILES.get('other_6_view'),
                other_7_view=request.FILES.get('other_7_view'),
                other_8_view=request.FILES.get('other_8_view'),
                address=data['address'],
                city=data['city'],
                state=data['state'],
                email=data['email'],
                phone_no=data['phone_no'],
                details=data['details'],
                price=data['price'])
           newfimp.save()
       return HttpResponseRedirect('/view_list/')
4

1 回答 1

0

你的done()方法不对。调用该done()方法时,django 已经验证了数据,您只需保存表单。

例如

def done(self, form_list, **kwargs):

    #you can access form as
    form1 = form_list[0]
    obj1 = form1.save(commit=False)

    #now set fields from 2nd form
    form2 = form_list[1]
    obj1.user = self.request.user
    obj1.address = form2.cleaned_data['address']
    ...

    obj1.save()

    return HttpResponseRedirect('/view_list/')
于 2013-05-30T10:14:37.180 回答