基于Django的博客系统之登录增加验证码校验(七)

个人登录增加验证码校验:

  • 描述: 在个人登录页面上添加验证码字段,以提高安全性,防止恶意登录和自动化攻击。
  • 规划:
    • 在登录表单中添加验证码输入字段。
    • 集成第三方验证码库,如 django-simple-captcha 或 django-recaptcha。
    • 后端验证用户输入的验证码是否正确,如果正确则允许登录,否则提示验证码错误。

技术实现步骤

步骤 1: 安装验证码库

选择并安装一个验证码库,比如 django-simple-captcha。你可以通过 pip 来安装:

bash 复制代码
pip install django-simple-captcha

步骤 2: 配置 django-simple-captcha

在你的 settings.py 文件中添加 captcha 到已安装的应用程序中:

python 复制代码
INSTALLED_APPS = [
    # 其它已安装的应用
    'captcha',
]

步骤 3: 创建验证码表单字段

在你的表单类中添加验证码字段。假设你已经有一个登录表单 LoginForm,现在你需要扩展它:

python 复制代码
from django import forms
from captcha.fields import CaptchaField

class LoginForm(forms.Form):
    username = forms.CharField(max_length=150)
    password = forms.CharField(widget=forms.PasswordInput)
    captcha = CaptchaField()  # 添加验证码字段

步骤 4: 更新登录视图

在你的视图中处理验证码的验证。如果使用类视图,可以这样做:

python 复制代码
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views import View
from .forms import LoginForm

class LoginView(View):
    def get(self, request):
        form = LoginForm()
        return render(request, 'login.html', {'form': form})

    def post(self, request):
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(request, username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')
            else:
                form.add_error(None, 'Invalid username or password')
        return render(request, 'login.html', {'form': form})

步骤 5: 更新模板

login.html模板中显示验证码字段。

html 复制代码
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="{% static 'blog/css/post_list.css' %}">
</head>
<body>
    <h2>Login</h2>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Login</button>
    </form>
</body>
</html>

步骤 6: 配置 URL

确保你的 urls.py 文件中包含验证码的URL配置:

python 复制代码
from django.urls import path
from .views import LoginView
from captcha.urls import urlpatterns as captcha_urls

urlpatterns = [
    path('login/', LoginView.as_view(), name='login'),
]

urlpatterns += captcha_urls

步骤 7: 测试

在本地开发环境中测试你的登录功能,确保验证码正确显示和验证:

  1. 运行开发服务器:

    bash 复制代码
    python manage.py runserver
  2. 在浏览器中访问登录页面,输入用户名、密码和验证码,确认一切工作正常。

    结果:

步骤 8: 增加点击验证码自动更新

login.html页面增加js代码,用来实现点击验证码自动更新。

js 复制代码
<script>
    // 当点击验证码图片时,刷新验证码
    $('.captcha').click(function () {
            $.getJSON('/captcha/refresh/',function (result) {
                $('.captcha').attr('src',result['image_url']);
                $('#id_captcha_0').val(result['key']);
            });
        });
</script>
相关推荐
偶遇急雨洗心尘25 分钟前
记录一次服务器迁移时,数据库版本不一致导致sql函数报错和系统redirect重定向丢失域名问题
运维·服务器·数据库·sql
计算机徐师兄26 分钟前
Python基于Django的MOOC线上课程推荐数据分析与可视化系统(附源码,文档说明)
python·数据分析·django·慕课线上课程推荐·慕课线上课程推荐可视化系统·pytho线上课程推荐可视化·线上课程推荐数据分析可视化系统
Arva .1 小时前
MySQL 的存储引擎
数据库·mysql
Logic1011 小时前
《Mysql数据库应用》 第2版 郭文明 实验5 存储过程与函数的构建与使用核心操作与思路解析
数据库·sql·mysql·学习笔记·计算机网络技术·形考作业·国家开放大学
小二·1 小时前
MyBatis基础入门《十六》企业级插件实战:基于 MyBatis Interceptor 实现 SQL 审计、慢查询监控与数据脱敏
数据库·sql·mybatis
bing.shao1 小时前
Golang WaitGroup 踩坑
开发语言·数据库·golang
专注VB编程开发20年1 小时前
C#内存加载dll和EXE是不是差不多,主要是EXE有入口点
数据库·windows·microsoft·c#
小二·1 小时前
MyBatis基础入门《十二》批量操作优化:高效插入/更新万级数据,告别慢 SQL!
数据库·sql·mybatis
何中应2 小时前
【面试题-6】MySQL
数据库·后端·mysql·面试题
路遥_132 小时前
银河麒麟 V10 安装部署瀚高数据库 HighGoDB 4.5 全流程(统信UOS Server 20同理)
数据库