Django 1.6:MultiValueDictKeyError错误
我正在尝试实现一个平均等待时间的功能,让用户可以输入医生的等待时间。但是我一直遇到这个错误,完全不知道该怎么解决。我试着查找资料,但还是搞不清楚。
Traceback:
File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
22. return view_func(request, *args, **kwargs)
File "views.py" in addWaitingTime
111. time = escape(post['time'])
File "/Library/Python/2.7/site-packages/django/utils/datastructures.py" in __getitem__
301. raise MultiValueDictKeyError(repr(key))
Exception Type: MultiValueDictKeyError at /waiting_time/
Exception Value: "'time'"
views.py
@login_required
def addWaitingTime(request):
post = request.POST
time = escape(post['time'])
doctor_seeker = post['userId']
doctor = post['doctorId']
if len(time) > 1:
newTime = WaitingTime(time=time, doctor_seeker_id = userId, doctor_id = doctorId)
newTime.save()
url = "/docprofile/"+str(doctor_id)+"/"
return HttpResponseRedirect(url)
models.py
class WaitingTime(models.Model):
time_choices = ( (10, 'Less than 10 Minutes'), (20, 'Less than 20 Minutes'), (30, 'Less than 30 Minutes'))
time = models.IntegerField(choices = time_choices)
doctor_id = models.IntegerField()
doctor_seeker_id = models.IntegerField()
def __unicode__(self):
return u"%s %s" % (self.time, self.doctor_id)
class Doctor(models.Model):
name = models.CharField(max_length=30)
specialization = models.ForeignKey(Specialization)
clinic = models.ForeignKey(Clinic)
class DoctorSeeker(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
user = models.OneToOneField(User, unique=True)
2 个回答
0
正如cchristelis所说,这个错误是因为你的POST数据里没有time
这个值。
其实对于这种情况,你应该使用Django的表单框架。这是验证用户输入和处理这些输入的正确工具。
1
问题是,帖子对象中没有名为'time'的变量。
我建议你:
1) 查看一下帖子对象的具体内容,可以通过打印出来或者写入文件的方式来查看。(我觉得你可能是用的get而不是post。)
2) 在处理用户输入的数据时,要始终做好准备,可能会和你预期的不一样。(比如,有恶意用户或者爬虫可能在访问你的网站。)最好使用:
time = post.get('time')
if time:
time = escape()
else:
# No time value was submitted ....