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

标签 python django django-forms django-views cleaned-data

我想在 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/

相关文章:

python - Django - 属性错误 : module 'os' has no attribute 'environment'

python - 无法更改应用引擎应用程序中的前端实例类

python - 在 Django 中保存表单数据

python - 如何返回 selenium 浏览器(或如何导入返回 selenium 浏览器的 def)

django - 未创建 uwsgi 套接字文件

python - Django 表单中的日期格式已更改

python - Django TypeError 'QueryDict' 对象不可调用

python - 保持 Django 模型清洁方法验证外键对象并使用 ModelForm 保存

python - 如何在python中访问编码(gb18020)字符串的一部分

python - 安装了 Nose 但不能在命令行上使用