【问题标题】:Django/python: How to pass the form.cleaned_data value to HttpResponseRedirect as an argument?Django/python:如何将 form.cleaned_data 值作为参数传递给 HttpResponseRedirect?
【发布时间】:2017-05-29 02:10:33
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

        你试过了吗?

        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()就足够了。

        【讨论】:

        • 由于您在保存实例之前不对其进行任何操作,因此您根本不需要使用commit=False 进行保存。使用instance = form.save() 保存表单,然后Phone = form.cleaned_data.get('Phone') 获取短信号码就足够了。
        • @Alasdair 我知道,但也许作者想做点什么)
        猜你喜欢
        • 1970-01-01
        • 2014-05-31
        • 2014-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-09
        相关资源
        最近更新 更多