string index out of range Python, Django

2024/11/16 18:39:03

i'm using Django to develop a web application. When i try and run it on my web form i am receiving 'string index out of range' error. However, when i hardcode a dictionary in to a python test file it works fine with the same values.

Here is my Django View:

def submitworkout(request):#workoutinfo = workout(request.GET)return render_to_response('home.html',{'infoprompt': workout(request.GET)},context_instance=RequestContext(request))

Here is the object:

class workout():def __init__(self,addworkout):self.workout = collections.OrderedDict();getallreps = 0for i in range(len(addworkout['exercisename'])): numsetcounter = 0; self.workout[string.capwords(addworkout['exercisename'][i])] = [] while numsetcounter < int(addworkout['numsets'][i]):   # print self.workout[addworkout['exercisename'][i]]self.workout[string.capwords(addworkout['exercisename'][i])].append([addworkout['weightinputboxes'][getallreps],addworkout['repinputboxes'][getallreps]]) #[getallreps +=1numsetcounter +=1  def getexercise(self,name): try: return self.workout[string.capwords(name)];except:return 'This exercise does not exist!'

Now this is the dictionary i'm trying to run through the class:

addworkout =    {u'repinputboxes': [u'5', u'3'], u'weightinputboxes': [u'195', u'170'], u'numsets': [u'1', u'1'], u'exercisename': [u'Squat', u'Power Clean']}

and here are the local vars that Django is displaying on the error:

i=1 numsetcounter =0getallreps = 1

Hopefull you guys help me resolve my problem. Thanks in advance!

EDIT: Traceback

Environment:Request Method: GET
Request URL: http://localhost:8000/submitworkout/?exercisename=Squat&numsets=1&weightinputboxes=195&repinputboxes=5&exercisename=Power+Clean&numsets=1&weightinputboxes=170&repinputboxes=3Django Version: 1.3.1
Python Version: 2.7.0
Installed Applications:
('django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.sites','django.contrib.messages','django.contrib.staticfiles','django.contrib.admin','authentication')
Installed Middleware:
('django.middleware.common.CommonMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware')Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Chris\testdjango\fitness\views.py" in submitworkout34.     return render_to_response('home.html',{'infoprompt': workout(request.GET)},context_instance=RequestContext(request))
File "C:\Users\Chris\testdjango\fitness\tracking\models.py" in __init__15.             while numsetcounter < int(addworkout['numsets'][i]):   # u'numsets': [u'1', u'2']Exception Type: IndexError at /submitworkout/
Exception Value: string index out of range
Answer

The problem is in the way you are using the QueryDict object from request.GET. A QueryDict is initialized from the request's query string. The way a list of values are passed in a GET request is like baz=1&baz=2. When you directly access the value by a key as if it were a normal dict, you are only ever getting the last value that was added.

Use the QueryDict properly using getlist:

exercises = addworkout.getlist('exercisename')
numsets = addworkout.getlist('numsets')

This will properly return lists of values.

Another option is to simply convert the QueryDict to a normal dict before passing it into your other method. This way it will have all the normal expanded values:

workout(dict(request.GET))

This is actually a really good idea because then your workout method won't have to have special knowledge of the QueryDict object. It can just treat it like a normal dict. It can then be used by any dictionary-like data structure besides a specific view-related situation.

https://en.xdnf.cn/q/119498.html

Related Q&A

PyQt UI event control segregation

I am a beginner in python but my OOPS concept from Java and Android are strong enough to motivate me in making some tool in python. I am using PyQt for developing the application. In my application th…

How to re-run process Linux after crash? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about a specific programming problem, a software algorithm, or s…

Number of pairs

I am trying to write a code that takes m. a, a list of integers n. b, an integer and returns the number of pairs (m,n) with m,n in a such that |m-n|<=b. So far, Ive got this def nearest_pairs(a, b):…

xml.etree.ElementTree.ParseError: not well-formed

I have the following code:from xml.etree import ElementTreefile_path = some_file_pathdocument = ElementTree.parse(file_path, ElementTree.XMLParser(encoding=utf-8))If my XML looks like the following it …

Convert nested XML content into CSV using xml tree in python

Im very new to python and please treat me as same. When i tried to convert the XML content into List of Dictionaries Im getting output but not as expected and tried a lot playing around.XML Content<…

How to decode binary file with for index, line in enumerate(file)?

I am opening up an extremely large binary file I am opening in Python 3.5 in file1.py:with open(pathname, rb) as file:for i, line in enumerate(file):# parsing hereHowever, I naturally get an error beca…

how to install pyshpgeocode from git [duplicate]

This question already has answers here:The unauthenticated git protocol on port 9418 is no longer supported(10 answers)Closed 2 years ago.I would like to install the following from Git https://github.c…

How to export dictionary as CSV using Python?

I am having problems exporting certain items in a dictionary to CSV. I can export name but not images (the image URL).This is an example of part of my dictionary: new = [{ "name" : "pete…

Passing values to a function from within a function in python

I need to pass values from one function to the next from within the function.For example (my IRC bot programmed to respond to commands in the channel):def check_perms(nick,chan,cmd):sql = "SELECT …

How to make Stop button to terminate start function already running in Tkinter (Python)

I am making a GUI using Tkinter with two main buttons: "Start" and "Stop". Could you, please, advise on how to make the "Stop" button to terminate the already running func…