0

我正在构建一些简单的东西,即在 Django 的列表中添加数字。但是,每当我尝试将浮点数的字符串值转换为浮点数时,它都会引发错误。在代码中更容易看到。

首先是我的观点:

def submitworkout(request):


       user =User.objects.get(username = request.session['username'])

       bodyweight =request.GET['weight']
       repinputboxes = request.GET['repinputboxes']
       totalreps = summation(list(repinputboxes))
       try: 
           float(bodyweight)

       except:
           bodyweight = None 
       w = workout(userid = user.id, datesubmitted =datetime.datetime.now(), workoutdate = request.GET['workoutdate'],
                    bodyweight = bodyweight, 
                    totalreps = totalreps, 
                    totalweight = summation(request.GET['weightinputboxes']),
                    numexercises = int(request.GET['numexercises']),
                    numsets = summation(request.GET['numsets']),
                    )
      # w.save()
      # workoutid = workout.objects.get(id = w.id)
       #createxercise(dict(request.GET),user.id,workoutid.id)  
       return render_to_response('home.html',{'infoprompt': request.GET},context_instance=RequestContext(request))


def summation(x):   
    suma = 0 

    for i in x: 
        suma += float(i)
    return suma 

接下来是回溯:

Environment:


Request Method: GET
Request URL: http://localhost:8000/submitworkout/?workoutdate=&weight=&numexercises=1&exercisename=b&numsets=1&weightinputboxes=32.5&repinputboxes=1

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',
 'tracking')
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
  45.                     totalweight = summation(request.GET['weightinputboxes']),
File "C:\Users\Chris\testdjango\fitness\views.py" in summation
  89.         suma += float(i)

Exception Type: ValueError at /submitworkout/
Exception Value: could not convert string to float: .

最后但并非最不重要的是我的本地 var 给了我这个问题:

weightinputboxes = u'32.5'

在此之前,我遇到了另一个像这样的奇怪错误: string index out of range Python, Django

我认为这与那个问题类似。但是,我仍然无法弄清楚。

多谢你们!

4

1 回答 1

1

最好使用内置的 sumgetlistrequest.GET sum(map(float, request.GET.getlist('weightinputboxes')))

于 2012-07-10T01:20:49.533 回答