1. 程式人生 > >Django商城項目筆記No.7用戶部分-註冊接口-判斷用戶名和手機號是否存在

Django商城項目筆記No.7用戶部分-註冊接口-判斷用戶名和手機號是否存在

ali UNC 直接 false pre ons func gis objects

Django商城項目筆記No.7用戶部分-註冊接口-判斷用戶名和手機號是否存在

判斷用戶名是否存在

技術分享圖片

後端視圖代碼實現,在users/view.py裏編寫如下代碼

技術分享圖片
class UsernameCountView(APIView):
    """
    判斷用戶名是否存在
    """
    def get(self, request, username):
        """
        獲取指定用戶名數量
        :param request:
        :return:
        """
        count = User.objects.filter(username=username).count()

        data 
= { "username": username, "count": count } return Response(data=data)
View Code

這裏沒有用到GenericAPIView,是因為邏輯本身就比較簡單,如果用GenericAPIView還得定義序列化器,所以就不用了,直接繼承APIView

前端實現,在js/register.js中修改

技術分享圖片
// 檢查用戶名
    check_username: function (){
            var len = this.username.length;
            
if(len<5||len>20) { this.error_name_message = ‘請輸入5-20個字符的用戶名‘; this.error_name = true; } else { this.error_name = false; } // 檢查重名 if (this.error_name == false) { axios.get(this.host + ‘/usernames/‘ + this
.username + ‘/count/‘, { responseType: ‘json‘ }) .then(response => { if (response.data.count > 0) { this.error_name_message = ‘用戶名已存在‘; this.error_name = true; } else { this.error_name = false; } }) .catch(error => { console.log(error.response.data); }) } },
View Code

判斷手機號是否存在

技術分享圖片

後端視圖代碼實現,在users/view.py裏編寫如下代碼

技術分享圖片
class MobileCountView(APIView):
    """
    判斷手機號是否存在
    """

    def get(self, request, mobile):
        """
        獲取指定手機號數量
        :param request:
        :return:
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            "mobile": mobile,
            "count": count
        }

        return Response(data=data)
View Code

前端實現,在js/register.js中修改

技術分享圖片
    // 檢查手機號
    check_phone: function (){
            var re = /^1[345789]\d{9}$/;
            if(re.test(this.mobile)) {
                this.error_phone = false;
            } else {
                this.error_phone_message = ‘您輸入的手機號格式不正確‘;
                this.error_phone = true;
            }
            if (this.error_phone == false) {
                axios.get(this.host + ‘/mobiles/‘+ this.mobile + ‘/count/‘, {
                        responseType: ‘json‘
                    })
                    .then(response => {
                        if (response.data.count > 0) {
                            this.error_phone_message = ‘手機號已存在‘;
                            this.error_phone = true;
                        } else {
                            this.error_phone = false;
                        }
                    })
                    .catch(error => {
                        console.log(error.response.data);
                    })
            }
        },
View Code

測試

技術分享圖片

技術分享圖片

Django商城項目筆記No.7用戶部分-註冊接口-判斷用戶名和手機號是否存在