gpt4 book ai didi

python - Django/python : How to pass the form. cleaned_data 值到 HttpResponseRedirect 作为参数?

转载 作者:太空宇宙 更新时间:2023-11-04 10:04:42 25 4
gpt4 key购买 nike

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

not enough arguments for format string

如果能帮助我解决这个问题,或者建议我将 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)

最佳答案

问题在于 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)

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

关于python - Django/python : How to pass the form. cleaned_data 值到 HttpResponseRedirect 作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41639103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com