inlineformset_factory由ModelForm组成

时间:2010-07-29 23:27:41

标签: django django-models django-forms

inlineformset_factory是否可以接受ModelForm以及模型。当我尝试运行它时,我收到一条错误消息'NoneType'对象不可迭代。

请帮助,我花了一整天的时间试图解决这个问题。感谢。

代码:

Model.py

class FilterForm(ModelForm):
firstFilter = forms.BooleanField(label='First Filter', initial=False, required=False)
class Meta:
    model = Filter
    exclude = ('order')


class Controller(models.Model):
protocol = models.CharField('Protocol',max_length=64, choices=PROTOCOLS, default='http')
server = models.CharField('Server', max_length=64, choices=SERVERS, default='127.0.0.1')
name = models.CharField('Name', max_length=64)

def __unicode__(self):
    return self.protocol + '://' + self.server + '/' + self.name

view.py

def controller_details(request, object_id):
controller = Controller.objects.get(pk=object_id)
controllerURI = controller.protocol + '://' + controller.server + '/' + controller.name
FilterFormSet = inlineformset_factory(Controller, FilterForm, extra=5)

if request.method == 'POST':
    formset  = FilterFormSet(request.POST, request.FILES, instance=controller)

    if formset.is_valid():
        filters = []

        # Save all the filters into a list
        forms = formset.cleaned_data
        for form in forms:
            if form:        
                protocol = form['protocol']
                server = form['server']
                name = form['name']
                targetURI = form['targetURI']
                filterType = form['filterType']
                firstFilter = form['firstFilter']

                if firstFilter == True:
                    aFilter = Filter(controller=controller, protocol=protocol, server=server, name=name, targetURI=targetURI, filterType=filterType, order=0)
                else:
                    aFilter = Filter(controller=controller, protocol=protocol, server=server, name=name, targetURI=targetURI, filterType=filterType, order=-1)

                filters.append(aFilter)

        # Find the first filter in the list of filters
        for index, aFilter in enumerate(filters):
            if aFilter.order == 0:
                break

        if filters[index].targetURI:
            test = "yes"
        else:
            for aFilter in filters:
                aFilter.save()

else:
    formset = FilterFormSet(instance=controller)

return render_to_response('controller_details.html', {'formset':formset, 'controllerURI':controllerURI}, context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:1)

更新:如果您打算使用Controller和Filter模型创建一个FormSet,其中Filter将FK保存到Controller,您需要:

FilterFormSet = inlineformset_factory(Controller, Filter, form=FilterForm)

请注意,在上面的代码中,您只传递了Controller模型类,这引起了一些混淆。