First install one of the required modules
pip install social-auth-app-django
After the installation, type pip list in the terminal and you will see
social-auth-app-django 3.1.0 social-auth-core 3.0.0
Then you can come to my github and download this demo about sliding captcha:/Edward66/slide_auth_code
Start the project after downloading
python runserver
After launching this project, you can see the example on the home page
front end
casually choose a (the bottom is mobile, do not do mobile do not choose) to copy the html and js code, I choose the pop-up. This should pay attention to his ajax request to send the URL, you can change this URL to their own view function corresponding to the URL, write their own logic inside, for example, I am in order to do the user login authentication, so I am writing the logic is to take the user to enter the account number, password and database to do the match.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>landing page</title> <link rel="stylesheet" href="/static/blog/css/slide_auth_code.css" rel="external nofollow" > <link rel="stylesheet" href="/static/blog/bs/css/" rel="external nofollow" > </head> <body> <h3>landing page</h3> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="popup"> <form > {% csrf_token %} <div class="form-group"> <label for="id_user">user ID:</label> <input name="user" class="form-control" type="text"> </div> <div class="form-group"> <label for="id_pwd">cryptographic:</label> <input name="pwd" class="form-control" type="password"> </div> <input class="btn btn-default" type="button" value="Submit"> <span ></span> <a href="{% url 'blog:register' %}" rel="external nofollow" class="btn btn-success pull-right">enrollment</a> </form> <div ></div> </div> </div> </div> </div> <script src="/static/blog/js/jquery-3.3."></script> <script src="/static/blog/js/"></script> <script src="/static/blog/js/slide_auth_code.js"></script>
let handlerPopup = function (captchaObj) { // Successful callbacks (function () { let validate = (); $.ajax({ url: "", // Perform secondary validation type: "post", dataType: "json", data: $('#fm').serialize(), success: function (data) { if () { = '/index/' } else { $('#error-info').text().css({'color': 'red', 'margin-left': '10px'}); setTimeout(function () { $('#error-info').text(''); }, 3000) } } }); }); $("#popup-submit").click(function () { (); }); // Add the captcha to the element with id captcha ("#popup-captcha"); // For more interface references: /install/sections/ }; // Authentication starts with getting id, challenge, success (with or without failback enabled) from the main backend of the site $.ajax({ url: "/pc-geetest/register?t=" + (new Date()).getTime(), // Add random numbers to prevent caching type: "get", dataType: "json", success: function (data) { // Using the initGeetest interface // Parameter 1: Configuration parameters // Parameter 2: Callback, the first parameter of the callback is the CAPTCHA object, which can be used later for events like appendTo. initGeetest({ gt: , challenge: , product: "popup", // Product forms, including: float, embed, popup. note that this only works for the PC version of CAPTCHA. offline: ! // Indicates that the user's background checks whether the GL server is down or not, which is generally not a concern. // For more configuration parameters see: /install/sections/#config }, handlerPopup); } });
Note: I am changing the url of the ajax request to the view function of the current page. Also the native code is all written in html, I made it decoupled. Also the native code uses jquery-1.12.3, I changed it to jquery-3.3.1 and it works fine.
back-end
Since the back-end logic is written in-house, only the pcgetcaptcha part of the code needs to be used here to handle the validation part.
First add the path to
from import path, re_path from import slide_code_auth # Slide CAPTCHA path('login/', ), re_path(r'^pc-geetest/register', slide_code_auth, name='pcgetcaptcha'), # slide_auth_codeI wrote the name myself.,The original name waspcgetcaptcha
I put the logic part of pcgetcaptcha into utils/slide_auth_code.py to use as a tool
utils/slide_auth_code.py
from import GeetestLib pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c" pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4" def pcgetcaptcha(request): user_id = 'test' gt = GeetestLib(pc_geetest_id, pc_geetest_key) status = gt.pre_process(user_id) [gt.GT_STATUS_SESSION_KEY] = status ["user_id"] = user_id response_str = gt.get_response_str() return response_str # pc_geetest_idcap (a poem)pc_geetest_keyunavoidable,If doing mobile to addmobile_geetest_idcap (a poem)mobile_geetest_key
from import auth from import render, HttpResponse from import JsonResponse from .slide_auth_code import pcgetcaptcha def login(request): if == "POST": response = {'user': None, 'msg': None} user = ('user') pwd = ('pwd') user = (username=user, password=pwd) if user: (request, user) response['user'] = else: response['msg'] = 'Username or password error' return JsonResponse(response) return render(request, '') # Slide CAPTCHA def slide_code_auth(request): response_str = pcgetcaptcha(request) return HttpResponse(response_str) def index(request): return render(request, '')
Note: You don't have to follow me, choose the appropriate features for your needs and modify them accordingly!
**Modify the code accordingly to use the slide validation to the registration page**
// Avatar preview function $('#id_avatar').change(function () { // the image changed, so use the change event // Get the user-selected file object let file_obj = $(this)[0].files[0]; // Get the path to the file object let reader = new FileReader(); // It's equivalent to getting the instance object in python. (file_obj); = function () { // Modify the src attribute of the img, src = path to the file object. $("#avatar_img").attr('src', ); // this is asynchronous and faster than the reader reading the path. // So wait for the reader to finish loading before executing it. }; }); // Ajax-based data submission let handlerPopup = function (captchaObj) { // Successful callbacks (function () { let validate = (); let formdata = new FormData(); // This is equivalent to instantiating an object in python. let request_data = $('#fm').serializeArray(); $.each(request_data, function (index, data) { (, ) }); ('avatar', $('#id_avatar')[0].files[0]); $.ajax({ url: '', type: 'post', contentType: false, processData: false, data: formdata, success: function (data) { if () { // Successful registration = '/login/' } else { // Failed to register // Empty the error message, each time before displaying the error message, clear the previous one. $('-info').html(""); $('.form-group').removeClass('has-error'); // Display the error message for this submission $.each(, function (field, error_list) { if (field === '__all__') { // Global error message, self-defined in global hooks $('#id_re_pwd').next().html(error_list[0]); } $('#id_' + field).next().html(error_list[0]); $('#id_' + field).parent().addClass('has-error'); // has-error is bootstrap-provided }); } } }) }); $("#popup-submit").click(function () { (); }); // Add the captcha to the element with id captcha ("#popup-captcha"); // For more interface references: /install/sections/ }; // Authentication starts with getting id, challenge, success (with or without failback enabled) from the main backend of the site $.ajax({ url: "/pc-geetest/register?t=" + (new Date()).getTime(), // Add random numbers to prevent caching type: "get", dataType: "json", success: function (data) { // Using the initGeetest interface // Parameter 1: Configuration parameters // Parameter 2: Callback, the first parameter of the callback is the CAPTCHA object, which can be used later for events like appendTo. initGeetest({ gt: , challenge: , product: "popup", // Product forms, including: float, embed, popup. note that this only works for the PC version of CAPTCHA. offline: ! // Indicates that the user's background checks whether the GL server is down or not, which is generally not a concern. // For more configuration parameters see: /install/sections/#config }, handlerPopup); } });
Write your own logic based on requirements
Summarize: slide validation is mainly used in the js part, just modify the value passed in the ajax is good, background logic to write their own.
The above is a small introduction to the use of python to realize the sliding CAPTCHA function, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. Here also thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!