Django Views.py 验证电话号码



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

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

目录: https://dpaste.org/sgyo

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

如何做到这一点?

(后续问题在这里:Django Forms.py 电子邮件和电话验证。

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 团队的这份文档。也许你,meknajirta,可以用我的片段来解决这个问题,然后继续遵循Bruno-desthuilliers的建议。发布后续问题,我们很乐意为您提供帮助。

最新更新