Django之BBS博客项目

Posted yinwenjie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django之BBS博客项目相关的知识,希望对你有一定的参考价值。

一、登陆功能(验证码)

 1 from geetest import GeetestLib
 2 from django.contrib import auth
 3 
 4 #使用极验滑动验证码的登陆
 5 def login(request):
 6     if request.method == "POST":
 7         #初始化一个返回给ajax的字典
 8         ret = {"status":0,"msg":""}
 9         #从提交的数据中获取用户名和密码
10         username = request.POST.get("username")
11         password = request.POST.get("password")
12         #获取验证码相关数据
13         gt = GeetestLib(pc_geetest_id, pc_geetest_key)
14         challenge = request.POST.get(gt.FN_CHALLENGE, ‘‘)
15         validate = request.POST.get(gt.FN_VALIDATE, ‘‘)
16         seccode = request.POST.get(gt.FN_SECCODE, ‘‘)
17         status = request.session[gt.GT_STATUS_SESSION_KEY]
18         user_id = request.session["user_id"]
19 
20         if status:
21             result = gt.success_validate(challenge, validate, seccode, user_id)
22         else:
23             result = gt.failback_validate(challenge, validate, seccode)
24 
25         #如果result有值,则验证成功,利用auth做验证
26         if result:
27             user = auth.authenticate(username=username,password=password)
28             if user:
29                 #如果用户名密码正确
30                 auth.login(request,user)
31                 ret["msg"] = "/index/"
32             else:
33                 ret["status"] = 1
34                 ret["msg"] = "用户名密码错误"
35         else:
36             #如果验证吗错误
37             ret["status"] = 1
38             ret["msg"] = "验证码错误"
39         return JsonResponse(ret)
40     return render(request,"login.html",locals())
41 
42 #请在官网申请ID使用,示例ID不可使用
43 pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
44 pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"
45 
46 #获取滑动验证码
47 def get_geetest(request):
48     user_id = test
49     gt = GeetestLib(pc_geetest_id, pc_geetest_key)
50     status = gt.pre_process(user_id)
51     request.session[gt.GT_STATUS_SESSION_KEY] = status
52     request.session["user_id"] = user_id
53     response_str = gt.get_response_str()
54     return HttpResponse(response_str)
  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
  7     <link rel="stylesheet" href="/static/css/mystyle.css">
  8 </head>
  9 <body>
 10 
 11 <div class="container">
 12     <div class="row">
 13         <form class="form-horizontal col-md-6 col-md-offset-3 login-form">
 14             {% csrf_token %}
 15             <div class="form-group">
 16                 <label for="username" class="col-sm-2 control-label">用户名</label>
 17                 <div class="col-sm-10">
 18                     <input type="text" class="form-control" id="username" name="username" placeholder="用户名">
 19                 </div>
 20             </div>
 21             <div class="form-group">
 22                 <label for="password" class="col-sm-2 control-label">密码</label>
 23                 <div class="col-sm-10">
 24                     <input type="password" class="form-control" id="password" name="password" placeholder="密码">
 25                 </div>
 26             </div>
 27             <div class="form-group">
 28                 <div id="popup-captcha"></div>
 29             </div>
 30             <div class="form-group">
 31                 <div class="col-sm-offset-2 col-sm-10">
 32                     <button type="button" class="btn btn-default" id="login-button">登录</button>
 33                     <span class="login-error"></span>
 34                 </div>
 35             </div>
 36         </form>
 37     </div>
 38 </div>
 39 
 40 
 41 <script src="/static/jquery.js"></script>
 42 <script src="/static/bootstrap/js/bootstrap.min.js"></script>
 43 <!-- 引入封装了failback的接口--initGeetest -->
 44 <script src="http://static.geetest.com/static/tools/gt.js"></script>
 45 <script>
 46     //发送数据
 47     var handlerPopup = function (captchaObj) {
 48     // 成功的回调
 49     captchaObj.onSuccess(function () {
 50         var validate = captchaObj.getValidate();
 51         var username = $("#username").val();
 52         var password = $("#password").val();
 53         $.ajax({
 54             url: "/login/", // 进行二次验证
 55             type: "post",
 56             dataType: "json",
 57             data: {
 58                 username: username,
 59                 password: password,
 60                 csrfmiddlewaretoken: $("[name=‘csrfmiddlewaretoken‘]").val(),
 61                 geetest_challenge: validate.geetest_challenge,
 62                 geetest_validate: validate.geetest_validate,
 63                 geetest_seccode: validate.geetest_seccode
 64             },
 65             success: function (data) {
 66                 if(data.status){
 67                     $(".login-error").text(data.msg);
 68                 }else{
 69                     location.href = data.msg;
 70                 }
 71             }
 72         });
 73     });
 74     //绑定事件显示滑动验证码
 75     $("#login-button").click(function () {
 76         captchaObj.show();
 77     });
 78     // 将验证码加到id为captcha的元素里
 79     captchaObj.appendTo("#popup-captcha");
 80     // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
 81 };
 82 
 83     // 验证开始需要向网站主后台获取id,challenge,success(是否启用failback)
 84     $.ajax({
 85         url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加随机数防止缓存
 86         type: "get",
 87         dataType: "json",
 88         success: function (data) {
 89             // 使用initGeetest接口
 90             // 参数1:配置参数
 91             // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
 92             initGeetest({
 93                 gt: data.gt,
 94                 challenge: data.challenge,
 95                 product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
 96                 offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
 97                 // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
 98             }, handlerPopup);
 99         }
100     });
101 
102 
103 </script>
104 </body>
105 </html>

二、注册功能(ajax上传数据)

 1 def register(request):
 2     if request.method == "POST":
 3         form_obj = RegisterForm(request.POST)
 4         ret = {"status": 0, "msg": ""}
 5         if form_obj.is_valid():
 6             form_obj.cleaned_data.pop("re_pwd")
 7             avatar = request.FILES.get("avatar")
 8             models.UserInfo.objects.create(**form_obj.cleaned_data,avatar=avatar)
 9             return JsonResponse(ret)
10         else:
11             ret["status"] = 1
12             ret["msg"] = form_obj.errors
13             return JsonResponse(ret)
14     form_obj = RegisterForm()
15     return render(request,"register.html",locals())

 

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>Title</title>
  6     <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
  7     <link rel="stylesheet" href="/static/css/mystyle.css">
  8 </head>
  9 <body>
 10 
 11 <div class="container">
 12     <div class="row">
 13         <form class="form-horizontal register-form" method="post" action="/register/" novalidate enctype="multipart/form-data">
 14             {% csrf_token %}
 15             <div class="form-group">
 16                <label for="{{ form_obj.username.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.username.label }}</label>
 17                 <div class="col-sm-4">
 18                     {{ form_obj.username }}
 19                     <span id="helpBlock2" class="help-block">{{ form_obj.username.errors.0 }}</span>
 20                 </div>
 21             </div>
 22 
 23             <div class="form-group">
 24                <label for="{{ form_obj.password.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.password.label }}</label>
 25                 <div class="col-sm-4">
 26                     {{ form_obj.password }}
 27                     <span id="helpBlock2" class="help-block">{{ form_obj.password.errors.0 }}</span>
 28                 </div>
 29             </div>
 30 
 31             <div class="form-group">
 32                <label for="{{ form_obj.re_pwd.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.re_pwd.label }}</label>
 33                 <div class="col-sm-4">
 34                     {{ form_obj.re_pwd }}
 35                     <span id="helpBlock2" class="help-block">{{ form_obj.re_pwd.errors.0 }}</span>
 36                 </div>
 37             </div>
 38 
 39             <div class="form-group">
 40                 <label for="{{ form_obj.email.id_for_label }}" class="col-sm-2 control-label">{{ form_obj.email.label }}</label>
 41                 <div class="col-sm-4">
 42                     {{ form_obj.email }}
 43                     <span id="helpBlock2" class="help-block">{{ form_obj.email.errors.0 }}</span>
 44                 </div>
 45             </div>
 46 
 47             <div class="form-group">
 48                <label class="col-sm-2 control-label">头像</label>
 49                 <div class="col-sm-4">
 50                     <label for="id_avatar"><img id="avatar-img" src="/static/avatar/default.png"></label>
 51                     <input type="file" name="avatar" id="id_avatar" style="display:none">
 52                     <span id="helpBlock2" class="help-block"></span>
 53                 </div>
 54             </div>
 55 
 56             <div class="form-group">
 57                 <div class="col-sm-offset-2 col-sm-10">
 58                     <button type="button" class="btn btn-success" id="register-btn">注册</button>
 59                 </div>
 60             </div>
 61         </form>
 62     </div>
 63 </div>
 64 
 65 
 66 <script src="/static/jquery.js"></script>
 67 <script src="/static/bootstrap/js/bootstrap.min.js"></script>
 68 <script>
 69 //获取头像,自动加载显示选中的头像
 70     $("#id_avatar").change(function(){
 71         //第一步、创建一个读取文件的对象
 72         var fileReader = new FileReader();
 73         //第二步、读取选中的文件
 74         fileReader.readAsDataURL(this.files[0]);
 75         //读取文件需要时间,所以要等到读取完文件,再进行下一步操作
 76         fileReader.onload = function(){
 77             //第三步、把图片加入img标签中
 78             $("#avatar-img").attr("src",fileReader.result)
 79         }
 80     });
 81 
 82 //ajax上传注册信息并获取错误信息
 83     $("#register-btn").click(function(){
 84 
 85         //ajax上传文件,data部分必须用对象
 86         var formData = new FormData();
 87         formData.append("username",$("#id_username").val());
 88         formData.append("password",$("#id_password").val());
 89         formData.append("re_pwd",$("#id_re_pwd").val());
 90         formData.append("email",$("#id_email").val());
 91         formData.append("avatar",$("#id_avatar")[0].files[0]);
 92         formData.append("csrfmiddlewaretoken",$("[name=‘csrfmiddlewaretoken‘]").val());
 93 
 94         $.ajax({
 95             url:"/register/",
 96             type:"post",
 97             //ajax上传文件需要加两个参数
 98             processData:false,
 99             contentType:false,
100             data:formData,
101             success:function(data){
102                 if(data.status){
103                     //如果有错误,则返回错误信息
104                     $.each(data.msg,function(k,v){
105                         //k是键,v是值,但是v是列表,错误信息可能有多个
106                         $("#id_"+k).next("span").text(v[0]).parent().parent().addClass("has-error");
107                     })
108                 }else{
109                     //如果没有错误,则跳转到指定页面
110                     location.href = "/login/"
111                 }
112             }
113         })
114     })
115 
116 //输入框取得焦点时,清楚错误信息
117     $("form input").focus(function(){
118         $(this).next("span").text("").parent().parent().removeClass("has-error");
119     });
120 
121 </script>
122 </body>
123 </html>

 

以上是关于Django之BBS博客项目的主要内容,如果未能解决你的问题,请参考以下文章

Django训练项目之BBS(博客项目)

django框架之BBS项目之文章详情和点赞

Django:之BBS项目

django框架之BBS项目之评论功能

项目开发流程

Python-Django-BBS