modelformset_factory generating "object has no attribute instance" error

45 views
Skip to first unread message

Farhan Khan

unread,
May 14, 2016, 10:34:38 PM5/14/16
to Django users
I am trying to display a modelformset_factory in a view, but am running into this error and unable to figure out why.

builtins.AttributeError
AttributeError: 'IPAddressForm' object has no attribute 'instance'

This seems to happen when I include this in my view: {{ ipaddressformset.as_table }}
This is generated from a modelformset_factory, which is from the model IPAddress and form IPAddressForm. 

I do not know what is causing this error! The full stack dump from the WSGI driver is here, but my code dump below might be more useful:

My view:
@login_required(login_url='/auth/')
def manualimport(request):
    IPAddressFormSet = modelformset_factory(IPAddress, form=IPAddressForm, exclude=())
    ipaddressformset = IPAddressFormSet( queryset=IPAddress.objects.none(), prefix='role' )
    if request.method == 'POST':
        assetform = AssetForm(request.POST)
        print("POST request")
        pass
    else:
        assetform = AssetForm()
    context = {'full_name': request.user.username,
               'assetform': assetform,
               'ipaddressformset': ipaddressformset}
    return render(request, 'asset/manualimport.html', context)
My form:

class IPAddressForm(forms.Form):
    address = forms.ChoiceField(required=True)
    new_address = forms.CharField(required=False)
    def __init__(self, *args, **kwargs):
        choices = ( ('','---'), (0,'Not Listed') )
        ipaddresses = IPAddress.objects.filter(component__isnull=True).distinct()
        for ipaddress in ipaddresses:
            choices = choices + ((ipaddress.id, ipaddress.address),)
        super(IPAddressForm, self).__init__(*args, **kwargs)
        self.fields['address'].choices = choices
        self.fields['address'].initial = ''

My template:

{{ ipaddressformset.management_form }}
{{ ipaddressformset.as_table }}

It appears to error out when the second line in the template is displayed. I do not know what the error is or what is causing it.

Please assist! Thanks.

PGP Fingerprint: 4A78 F071 5CB6 E771 B8D6 3910 F371 FE22 3B20 B21B
Reply all
Reply to author
Forward
0 new messages