以为是我的代码,我利用阿里云短信和ajax实现了给手机发送短信,但现在只能给阿里云绑定测试的手机号发送验证码,而不能使输入的手机号都可以发送验证码,我该如何修改?
前端代码
<html>
<head>
<meta http-equiv="content-type" content="text/html;
charset=UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1, maximum-scale=1,user-scalable=no">
<title>注册</title>
{% load static %}
<link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css'%}">
<link rel="stylesheet" href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.css'%}">
<link rel="stylesheet"
href="{% static 'plugins/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css'%}">
</head>
<body>
<div class="account">
<h2 style="text-align:center;">用户注册</h2>
<form id="regForm" method="POST" style="margin-top:20px;" novalidate>
{% csrf_token %}
{% for field in form %}
{% if field.name == 'code' %}
<div class="form-group" style="margin-top:20px;">
<label> {{ field.label}}</label>
<div class="clearfix">
<div class="col-md-6" style="padding:0;">{{field}}</div>
<div class="col-md-6"><input id="btnSms" type="button" class="btn btn-default" value="点击获取验证码"></div>
</div>
<span class="error-msg" style="color:red;position:absolute"></span>
</div>
{% else %}
<div class="form-group" style="margin-top:20px;">
<label> {{ field.label}}</label>
{{field}}
<span class="error-msg" style="color:red;position:absolute"></span>
{% endif %}
{%endfor%}
<div>
<input id="btnSubmit" style="height:35px;width:200px; margin-left:90px; font-size:17px;" type="button" value="注册"
class="btn btn-info">
</div>
<div>
<span style="float: right; margin-top:20px;">已有账号.<a style=" text-decoration:none;" href=" ">去登录</a ></span>
</div>
</div>
</form>
</div>
<script src="{% static 'js/jquery-3.5.1/jquery-3.5.1.min.js'%}"></script>
<script>
//页面加载完
$(function(){
bindClickBtnSms();
});
//点击获取验证码的按钮绑定事件
function bindClickBtnSms(){
$('#btnSms').click(function(){
$(".error-msg").empty();
//获取用户输入的手机号
var mobile=$('#id_mobile').val();
$.ajax({
url:"/send/sms/",
type:"GET",
data:{mobile: mobile,tpl: "register"},
dataType: 'json',
success:function(res){
//ajax请求发送成功后,自动执行函数
if (res.status){
sendSmsRemind();
}else{
//错误信息
$.each(res.error,function(key,value){
$('#id_'+key).next().text(value[0]);
})
}
},
error:function(xhr,status,error){
console.log('ajax请求失败:'+error)}
})
})
}
//倒计时
function sendSmsRemind() {
var $smsBtn=$('#smsBtn');
$smsBtn.prop('disabled',true); //禁用
var time =60;
var remind=setInterval(function (){
$smsBtn.val(time + '秒重新发送');
time=time-1;
if (time<1){
clearInterval(remind);
$smsBtn.val('点击获取验证码').prop('disabled',false);
}
},1000)
}
</script>
</body>
</html>
后端代码
def send_sms_lingle(phone_num, template_code, template_param):
client = create_client('LTAI5tBxR8DkU1BKW39QsiLK', 'TEjXlIqcV31dBwwW8gHqUA6xVSr4DO')
send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
sign_name='Python图书管理',
template_code=template_code,
phone_numbers=phone_num,
template_param=template_param
)
runtime = util_models.RuntimeOptions()
try:
response = client.send_sms_with_options(send_sms_request, runtime)
return response
except Exception as error:
UtilClient.assert_as_string(error.message)
return {'result': 1000, 'errmsg': "短信发送失败"}
class SendSmsForm(forms.Form):
code = random.randrange(100000, 999999)
mobile = forms.CharField(label="手机号",
validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])
def __init__(self, request, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request = request
def clean_mobile(self):
"""手机号校验的勾子"""
mobile = self.cleaned_data['mobile']
# 判断短信模板是否有问题
tpl = self.request.GET.get('tpl')
template_id = settings.ALIYUN_SMS_TEMPLATE.get(tpl)
if not template_id:
raise ValidationError("短信模板错误")
# 校验数据库中是否已有手机号
exist = Username.objects.filter(mobile=mobile).exists()
if exist:
raise forms.ValidationError('手机号已存在')
# 发短信 & 写redis
code = random.randrange(100000, 999999)
send_sms_lingle(mobile, template_id, '{"code":"' + str(code) + '"}')
return mobile
def create_client(access_key_id, access_key_secret):
config = open_api_models.Config(
access_key_id=access_key_id,
access_key_secret=access_key_secret
)
config.endpoint = f'dysmsapi.aliyuncs.com'
return Dysmsapi20170525Client(config)
def send_sms(request):
"""发送短信"""
from library.utils.forms import SendSmsForm
form = SendSmsForm(request, data=request.GET)
# 校验手机号,不能为空
if form.is_valid():
return JsonResponse({'status': True})
return JsonResponse({'status': False, 'error': form.errors})