1. 程式人生 > >Django 部落格系統------登入註冊功能

Django 部落格系統------登入註冊功能

一、登入:

urls配置:註冊中需要圖片,

url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),

登入login只需用auth驗證一下即可,加了個驗證碼,沒啥難度。

驗證碼程式碼需要使用PIL模組.

pip3 install pillow

驗證碼的引用原理:在HTML中img標籤請求一個url指向URL生成函式獲取驗證碼圖片。

    url(r'^get_validCode_img/',views.get_validCode_img),

Python程式碼

def get_validCode_img(request):
    '''
生成驗證碼圖片''' img = Image.new(mode="RGB", size=(120, 40), color=(random.randint(200,255),random.randint(200,255),random.randint(200,255))) draw=ImageDraw.Draw(img,"RGB") font=ImageFont.truetype("blog/static/font/kumo.ttf",25) valid_list=[] for i in range(5): #生成驗證碼 random_num=str(random.randint
(0,9)) random_lower=chr(random.randint(65,90)) random_upper=chr(random.randint(97,122)) random_char=random.choice([random_num,random_lower,random_upper]) draw.text([5+i*24,10],random_char,(random.randint(0,200),random.randint(0,200),random.randint(0,200)),font=font) valid_list.append
(random_char) for i in range(100): #生成噪點 draw.point([random.randint(0,120),random.randint(0,40)], fill=(random.randint(0,255),random.randint(0,255),random.randint(0,255))) f=BytesIO() img.save(f,"png") data=f.getvalue() valid_str="".join(valid_list) print(valid_str) request.session["keepValidCode"]=valid_str return HttpResponse(data)

網頁中

<div class="col-md-6">
                        <img class="validCode_img" src="/get_validCode_img/" alt="" width="170px" height="40px">
                    </div>

驗證碼重新整理:

   $(".validCode_img").click(function () {
        $(this)[0].src += "?"

    })
    在url後面加?重新發送一次請求即可重新整理驗證碼

二、註冊

註冊使用form表單來進行資料驗證:

forms:

class RegForm(forms.Form):
    username = forms.CharField(max_length=12, min_length=5, required=True, error_messages={"required": "不能為空", },
                               widget=widgets.TextInput(attrs={"class": "form-control", "placeholder": "使用者名稱長度不能小於5大於15"}))

    password = forms.CharField(min_length=6, error_messages={"required": "不能為空", },
                               widget=widgets.PasswordInput(attrs={"class": "form-control", "placeholder": "密碼不能為純數字或字母且長度大於6"}))

    repeat_pwd = forms.CharField(min_length=6, error_messages={"required": "不能為空", },
                                 widget=widgets.PasswordInput(attrs={"class": "form-control", "placeholder": "再次輸入密碼"}))

    email = forms.EmailField(error_messages={"required": "不能為空", },
                             widget=widgets.EmailInput(attrs={"class": "form-control", "placeholder": "郵箱"}))

    def clean_username(self):

        ret = models.UserInfo.objects.filter(username=self.cleaned_data.get("username"))
        if not ret:
            return self.cleaned_data.get("username")
        else:
            raise ValidationError("使用者名稱已註冊")

    def clean_password(self):
        data = self.cleaned_data.get("password")
        if not data.isdigit():
            return self.cleaned_data.get("password")
        else:
            raise ValidationError("密碼不能全是數字")

    def clean(self):
        if self.cleaned_data.get("password") == self.cleaned_data.get("repeat_pwd"):
            return self.cleaned_data

        else:
            raise ValidationError("兩次密碼不一致")

Views:

def reg(request):
    if request.method == "GET":
        form_obj = forms.RegForm(request)
        return render(request, "reg.html", {"form_obj": form_obj})
    if request.is_ajax():
        form_obj=forms.RegForm(request,request.POST)
        regResponse={"user":None,"errorsList":None}
        if form_obj.is_valid():
            username=form_obj.cleaned_data["username"]
            password=form_obj.cleaned_data["password"]
            email=form_obj.cleaned_data.get("email")
            avatar_img=request.FILES.get("avatar_img")
            user_obj=models.UserInfo.objects.create_user(username=username,password=password,email=email,avatar=avatar_img,nickname=username)
            regResponse["user"]=user_obj.username
        else:
            regResponse["errorsList"]=form_obj.errors
        return HttpResponse(json.dumps(regResponse))

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Title</title>

    <script src="/static/dist/js/jquery-3.1.1.js"></script>
    <script src="/static/dist/js/bootstrap.js"></script>

    <link rel="stylesheet" href="/static/dist/css/bootstrap.css">

    <link rel="stylesheet" href="/static/css/reg.css">
    <script src="/static/js/jquery.cookie.js"></script>
</head>
<body>



<div class="container">
    <div class="row">
        <div class="col-md-5 col-md-offset-3">
            <h2 class="text-center">歡迎註冊</h2>
            <form>
                      {% csrf_token %}
                      <div class="form-group">
                        <label for="username">使用者名稱</label>
                        {{ form_obj.username }}
                      </div>
                      <div class="form-group">
                        <label for="password">密碼</label>
                        {{ form_obj.password }}
                      </div>

                       <div class="form-group">
                        <label for="password">確認密碼</label>
                           {{ form_obj.repeat_pwd }}
                      </div>

                      <div class="form-group">
                        <label for="email">郵箱</label>
                          {{ form_obj.email }}
                      </div>

                      <div class="form-group avatar">
                        <label for="avatar">頭像</label>
                        <img src="/static/img/default.png" alt="" id="avatar_img">
                        <input type="file" class="form-control" id="avatar_file" >
                      </div>


                    <input type="button" value="註冊" class="btn btn-primary col-lg-3" id="subBtn"><span class="error"></span>

                </form>
        </div>
    </div>
</div>

<script>
    // 頭像預覽

    $("#avatar_file").change(function () {

        var ele_file=$(this)[0].files[0];  //this.files
        var reader=new FileReader();
        reader.readAsDataURL(ele_file);
        reader.onload=function () {
            $("#avatar_img")[0].src=this.result
        }

    });

    $("#subBtn").click(function () {

        var formdata=new FormData();
        formdata.append("username",$("#id_username").val());
        formdata.append("password",$("#id_password").val());
        formdata.append("repeat_pwd",$("#id_repeat_pwd").val());
        formdata.append("email",$("#id_email").val());
        formdata.append("avatar_img",$("#avatar_file")[0].files[0]);

        $.ajax({
            url:"/reg/",
            type:'POST',
            data:formdata,
            contentType:false,
            processData:false,
            headers:{"X-CSRFToken":$.cookie('csrftoken')},
            success:function (data) {
                  console.log(data);
                var data=JSON.parse(data);

                if (data.user){
                    location.href="/login/"
                }
                else {

                    console.log(data.errorsList);

                   $.each(data.errorsList,function (i,j) {
                       console.log(i,j);

                       $span=$("<span>");
                       $span.addClass("pull-right").css("color","red");
                       $span.html(j[0]);
                       $("#id_"+i).after($span).parent().addClass("has-error");

                       if (i=="__all__"){
                            $("#id_repeat_pwd").after($span)
                       }
                   })


                }


            }
        })
    })
</script>



</body>
</html>