1

我正在浏览 Django 教程,我想弄清楚如何从浏览器发布对模型的更改。这是网址:

 url(r'^(?P<person_id>\d+)/updatePerson/$', views.updatePerson, name='updatePerson')                       
)

这是视图:

def updatePerson(request, person_id):
    p = get_object_or_404(Person, pk=person_id)
#    try:
#        user = p.get(pk=request.POST['name'])
#    except (KeyError, Person.DoesNotExist):
        # Redisplay the poll voting form.
#        return render(request, 'maps/detail.html', {
#            'person': p,
#            'error_message': "This person does not exist",
#        })
    #else:
    p.lat = request.POST['lat']
    p.lon = request.POST['lon']
    p.task = request.POST['task']
    p.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
    return HttpResponseRedirect(reverse('maps:detail', args=(p.id,)))

我尝试的网址是:

<serveraddress>/maps/1/updatePerson/?lat=20&lon=20&task=hangOut

我收到此错误:

    MultiValueDictKeyError at /maps/1/updatePerson/
"Key 'lat' not found in <QueryDict: {}>"
Request Method: GET
Request URL:    <serveraddress>/maps/1/updatePerson/?lat=20
Django Version: 1.5.2
Exception Type: MultiValueDictKeyError
Exception Value:    
"Key 'lat' not found in <QueryDict: {}>"
Exception Location: D:\Python\lib\site-packages\django\utils\datastructures.py in __getitem__, line 295
Python Executable:  D:\Python\python.exe
Python Version: 2.7.5
Python Path:    
['C:\\GXM_LABS\\gxm_maps',
 'D:\\Python\\lib\\site-packages\\setuptools-1.1.3-py2.7.egg',
 'D:\\Python\\lib\\site-packages\\django_evolution-0.6.9-py2.7.egg',
 'D:\\Python\\lib\\site-packages\\south-0.8.2-py2.7.egg',
 'C:\\Windows\\system32\\python27.zip',
 'D:\\Python\\DLLs',
 'D:\\Python\\lib',
 'D:\\Python\\lib\\plat-win',
 'D:\\Python\\lib\\lib-tk',
 'D:\\Python',
 'D:\\Python\\lib\\site-packages']
Server time:    Sat, 7 Sep 2013 16:42:14 -0400

我应该在我的 url 定义中做一个正则表达式来捕获这些值吗?还是我不正确地接近这个?我正在与教程一起工作,但修改它们以适应我正在做的一些工作。我真的不想要用户输入的表单,因为从长远来看,我将从远程位置(智能手机)发布这些数据,因此实际上能够提交这些数据的网页对我来说没有那么有趣直接发布这些更改的能力。

4

1 回答 1

1

request.GET您应该从而不是 a读取查询参数,request.POST因为您正在发出 GET 请求(请参阅Request Method: GET错误页面)。

仅供参考,还有request.REQUEST字典可用:

为方便起见,类似字典的对象先搜索 POST,然后再搜索 GET。受 PHP 的 $_REQUEST 启发。

但是,使用它不是一个好习惯。最好是明确的。

于 2013-09-07T20:57:34.393 回答