Skip to main content
 首页 » 编程设计

python之提交空表格和奇怪的输出

2025年05月04日13soundcode

这是我的表格:

<form action = "/search/" method = "get"> 
    <input type = "text" name = "q"> 
    <input type = "submit" value = "Search"> 
</form> 

这是我的观点:

def search(request): 
    if 'q' in request.GET: 
        message = 'You searched for: %r' % request.GET['q'] 
    else: 
        message = 'You submitted an empty form :(' 
    return HttpResponse(message) 

当我尝试输入一些东西时,一切正常,除了奇怪的东西。例如,当我输入 asdasda 时,我得到输出 You searched for: u'asdsa'。另一个问题是,当我提交一个空表单时,输出只是u'',而它应该是“你提交了一个空表单:(”。我正在阅读“The Django Book”, 1.x.x 版本,这是一个例子..

请您参考如下方法:

“weird u thing”是一个 unicode 字符串。您可以在这里阅读:http://docs.python.org/tutorial/introduction.html#unicode-strings

我猜自从用户按下提交后,您会收到一个具有空 q 值 (u'') 的请求,因为用户没有输入任何内容。这是有道理的,对吧?您应该更改您的 if 语句来检查这个空的 unicode 字符串。