字符串索引超出Python,Django [英] string index out of range Python, Django
问题描述
这是我的Django视图:
def submitworkout(request) :
#workoutinfo = workout(request.GET)
return render_to_response('home.html',{'infoprompt':workout(request.GET)},context_instance = RequestContext(request))
这是对象:
code> class workout():
def __init __(self,addworkout):
self.workout = collections.OrderedDict();
getallreps = 0
对于我的范围(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 + = 1
numsetcounter + = 1
def getexercise(self,name):
try:
return self.workout [string.capwords(name)];
除了:
返回'此练习不存在!'
现在这个是我正在尝试通过课程的字典:
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']}
这里是Django的本地vars显示错误:
i = 1
numsetcounter = 0
getallreps = 1
希望你们帮我解决问题。提前致谢!
编辑:追溯
环境:
请求方法:GET
请求URL:http:// localhost:8000 / submitworkout /?exercisename = Squat& numsets = 1& weightinputboxes = 195& repinputboxes = 5& exerciseisename = Power + Clean& numsets = 1& weightinputboxes = 170& repinputboxes = 3
Django版本:1.3.1
Python版本:2.7.0
安装的应用程序:
('django。 contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib。消息',
'django.contrib.staticfiles',
'django.contrib.admin',
'authentication')
安装的中间件:
('django。 middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware。 AuthenticationMiddleware',
'django.contri b.messages.middleware.MessageMiddleware')
追溯:
文件C:\Python27\lib\site-packages\django\core\ get_response
111. response = callback(request,* callback_args,** callback_kwargs)
文件C:\Users\Chris\testdjango\fitness\ submit.py
34. return render_to_response('home.html',{'infoprompt':workout(request.GET)},context_instance = RequestContext(request))
文件C:\\ _Usin\Chris\testdjango\fitness\tracking\models.py__init__
15.而numsetcounter < int(addworkout ['numsets'] [i]):#u'numsets':[u'1',u'2']
异常类型:IndexError at / submitworkout /
异常值:字符串索引超出范围
问题是您正在使用 QueryDict 对象 request.GET中
。 QueryDict从请求的查询字符串初始化。在GET请求中传递值列表的方式就像 baz = 1& baz = 2
。当您直接通过密钥访问该值时,就像它是一个普通的dict,你只会得到最后添加的值。
使用QueryDict正确使用<一个href =https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.QueryDict.getlist =nofollow> getlist :
exercise = addworkout.getlist('exercisename')
numsets = addworkout.getlist('numsets')
这将正确返回值列表。
另一个选项是简单将QueryDict转换为正常的dict,然后将其传递给您的其他方法。这样,它将具有所有正常的扩展值:
workout(dict(request.GET))
这实际上是一个很好的主意,因为您的锻炼方法不必具有QueryDict对象的特殊知识。它可以像一个正常的命令一样对待它。除了特定的视图相关情况,它可以被任何类似字典的数据结构所使用。
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 = 0
for 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 +=1
numsetcounter +=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 =0
getallreps = 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=3
Django 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_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Chris\testdjango\fitness\views.py" in submitworkout
34. 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
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.
这篇关于字符串索引超出Python,Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!