【问题标题】:Django Views.py Validate Phone NumberDjango Views.py 验证电话号码
【发布时间】:2020-04-05 12:22:24
【问题描述】:

我想使用 django-phonenumber-field 之类的方法或其他方法,但如果用户没有以 + 的格式提供有效的国际电话号码,则只能让 views.py 能够验证或显示错误消息以 12125552368 为例。

此表单不使用 models.py 或 forms.py,如果可能,我希望将所有内容保留在 views.py 中。也不想为了安全和人们禁用它的原因使用 JavaScript。

HTML: https://dpaste.org/sgyo

Views.py: https://dpaste.org/vjZZ

如何做到这一点?

(这里有一个后续问题:Django Forms.py Email And Phone Validation。)

【问题讨论】:

  • 为什么不想使用表单?这将使您的表单处理和扩展您的视图更清晰
  • 实际上使用django表单的原因很少。并且通过各种方式将这个可怕的东西拆分为可读、可管理、可测试的函数,并学习进行适当的异常处理——一个围绕两个复杂调用的裸异常子句,每个调用都有数百个失败原因,然后假设它会失败的唯一原因失败是“付款已被拒绝”是您能做的最糟糕的事情。
  • @Lain Shelvington 和 bruno - 好的,我明白你的观点了。如果你这么坚持,你能帮我将我的代码转换为使用 forms.py 吗?如果没有,你能帮我编写代码以使用 django-phonenumbers 使用 python-phonenumbers 使用下面给出的示例,但使用我的代码实现它吗?我遇到了麻烦。
  • @bruno desthuilliers 我正在尝试做 forms.py 现在我以为我做了所有事情,但是这些字段没有显示在网页上。 dpaste.org/akbh我可以帮忙吗?
  • @brunodesthuilliers 更新我得到了要显示在网页上的字段,但现在表单没有提交,验证错误也没有显示在页面上。 dpaste.org/22SV

标签: python django validation


【解决方案1】:

django-phonenumbers 使用python-phonenumbers。由于您想跳过表单并直接在视图中工作,因此您可以完全跳过 Django 包;使用 Python 包。从文档中,这是一个示例:

>>> import phonenumbers
>>> x = phonenumbers.parse("+442083661177", None)
>>> print(x)
Country Code: 44 National Number: 2083661177 Leading Zero: False
>>> type(x)
<class 'phonenumbers.phonenumber.PhoneNumber'>
>>> y = phonenumbers.parse("020 8366 1177", "GB")
>>> print(y)
Country Code: 44 National Number: 2083661177 Leading Zero: False
>>> x == y
True
>>> z = phonenumbers.parse("00 1 650 253 2222", "GB")  # as dialled from GB, not a GB number
>>> print(z)
Country Code: 1 National Number: 6502532222 Leading Zero(s): False

https://github.com/daviddrysdale/python-phonenumbers#example-usage

这是您的代码中的外观草图:

首先,安装phonenumberspip install phonenumbers

<form action="." method="post" id="payment-form">
  {% csrf_token %}

  ...

  <label for="phone"> Phone: </label>
  {% if not validated_phone_number %} 
    <input id="phone" name="phone" value="" class="form-control" autocomplete="off" type="tel" required />
  {% else %}
    <div id="phone">{{ validated_phone_number }}
  {% endif %}

  ...

</form>
# views.py
import phonenumbers

def PaymentView(request):

    ...

    if request.method == "POST":
        ...

        phonenum_input = request.post.get('phone')

        try:
            phonenum = phonenumbers.parse(phonenum_input)
        except phonenumbers.phonenumberutils.NumberParseException:
            messages.warning(
                request, "The phone number is not valid."
            )
            context = {
                'publishKey': publishKey,
                'selected_membership': selected_membership,
                'amend': "true",
                "client_secret": payment_intent.client_secret,
                "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLISHABLE_KEY,
                "subscription_id": stripe_subscription.id
            }

            return render(request, "memberships/3d-secure-checkout.html", context)

        else: # We now assume the number is valid.
            context.update({'valid_phone_number': phonenum})

        ...
            return render(request, "memberships/membership_payment.html", context)

(对于您和查看这篇文章的其他人来说,使用 Django 表单库确实会更好,因为上面 bruno-desthuilliers 突出显示的原因。阅读 Django 团队的 this doc。也许你,meknajirta,可以使用我的 sn-ps 进行此操作,然后继续遵循 bruno-desthuilliers 的建议。发布后续问题,我们很乐意提供帮助。)

【讨论】:

  • 但是,如 cmets 中所述,使用 Django 的表单会更容易,除非您有其他限制。
  • 谢谢你给我看这个。我只是不确定如何用我的代码实现它。你能告诉我怎么做吗?我找到了这个programcreek.com/python/example/104094/phonenumbers.parse,但是如何将它与模板中的 id 连接起来?
  • @meknajirta:我更新了答案,包括了你的代码可能是什么样子的草图。您链接到的帖子也有很好的例子。在您拥有上述模板并查看设置后,请按照他们的指示进行操作。
  • 哇,谢谢你这么详细的回复!我用你的方法真的很接近。唯一的事情是电话号码错误消息在网站的完全不同部分而不是表单本身进行付款后显示 - 它不会阻止付款的发生。如何让错误消息显示在表单上?回应你的其他东西,听起来像是一个计划。 dpaste.org/…
  • 我现在正在尝试做 forms.py,但我遇到了麻烦。表单字段未显示在网页上。我可以在这方面以及我们真正接近的上述views.py方面获得一些帮助吗? dpaste.org/akbh
猜你喜欢
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-20
  • 2011-02-03
  • 2011-09-05
相关资源
最近更新 更多