1

我想在 URL 中传递一个参数(表单字段值),如下所示。但是当我这样做时,它会引发一个错误

格式字符串的参数不足

我会很感激帮助我解决这个问题,或者建议我一种将 form_cleaned 值传递给 HttpResponseRedirect 的替代方法。

def phone(request):
    form = PhoneForm(request.POST or None)
    if form.is_valid():

        instance = form.save(commit=False)
        Phone = form.cleaned_data.get('Phone')
        instance.save()
        form.save()
        return HttpResponseRedirect('http://send_sms.com/api_key=api&to=%s&message=Welcome%20to%messaging' %Phone)

    context = {
    "form": form,
    }
    return render(request, "phone.html", context)
4

3 回答 3

2

问题是 Python 也将%字符串中的其他符号视为占位符。

您可以将其他百分号加倍(例如Welcome%%20),或使用.format(Phone),但更安全的方法是让 Python 负责为您编码查询字符串。

from urllib.parse import urlencode # Python 3
# from urllib import urlencode # Python 2

query = {
   'api_key': 'api',
   'to': Phone,
   'message': 'Welcome to messaging',
}
url = 'http://send_sms.com/?%s' % urlencode(query)
return HttpResponseRedirect(url)

希望这更具可读性并减少出错的机会。例如,在您的问题中,您有%而不是%20in %messaging

于 2017-01-13T16:40:11.787 回答
1

你试过这个吗?

from urllib.parse import urlencode # Python 3
# from urllib import urlencode # Python 2

def phone(request):
    form = PhoneForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        argument = form.cleaned_data.get('Phone')
        instance.save()
        # form.save() -- redundant here imho
        return HttpResponseRedirect(
        'http://send_sms.com/api_key=api&to={}&message=Welcome%20to%messaging'.format(urlencode(argument))
        )

    context = {
       "form": form,
    }
    return render(request, "phone.html", context)

您正在使用过时的格式进行字符串替换。而且您也不需要form.save,因为您的表单是一个实例,所以instance.save()就足够了。

于 2017-01-13T16:32:36.513 回答
1

您可以尝试使用这种格式:

return HttpResponseRedirect('http://send_sms.com/api_key=api&to={}&message=Welcome%20to%messaging'.format(Phone))

您正在使用的字符串替换已过时。对于长期解决方案,这可能是更好的方法。

于 2017-01-13T16:34:42.490 回答