首页 > 解决方案 > Django Views.py 验证电话号码

问题描述

我想使用 django-phonenumber-field 之类的方法或其他方法,但如果用户没有提供 +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。)

标签: pythondjangovalidation

解决方案


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

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

首先,安装phonenumbers: pip 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 团队阅读这个文档。也许你,meknajirta,可以让这个工作使用我的片段,然后继续遵循 bruno-desthuilliers 的建议。发布后续问题,我们将很乐意提供帮助。)


推荐阅读