Aditya Singh Aditya Singh - 5 months ago 17
Python Question

string index out of range django

I am trying to iterate for an array but it throws the above error

here is the view:

brand_category = self.request.POST.get('parameter[]')
for D in brand_category:
print brand_category
brands, categories = D[0] , D[1]
print brands , categories

looks like this:


here is the traceback:

File "C:\Python27\lib\site-packages\django\core\handlers\" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\" in view
71. return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django\views\generic\" in dispatch
89. return handler(request, *args, **kwargs)
File "C:\Users\lenovo\Desktop\Grooved2\grooved\src\sellers\" in post
329. brands, categories = D[0] , D[1]


First of all, brand_category is not an array but a dictionary. If you do for D in brand_category, you were just looping through the keys. To loop the dictionary properly, do:

for brand, categories in brand_category.iteritems():
    print brand, categories

If you want to loop on the values which are lists, do:

for brand, categories in brand_category.iteritems():
    print brand
    for category in categories:
        print category