基于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>
相关推荐
cfm_29149 分钟前
SpringBoot 数据库全栈整合
数据库·spring boot·后端
是上好佳佳佳呀18 分钟前
MySQL 基础:从数据库概念到表结构管理DDL
数据库·mysql
Nturmoils20 分钟前
Oracle 迁移评估时,我把这两类问题列在了检查清单最前面
数据库
Database_Cool_32 分钟前
数据库性能不够用,升级到什么方案好?阿里云 PolarDB(云原生数据库领导者,兼容 MySQL/PostgreSQL/Oracle)平滑升级与百倍弹性
数据库·阿里云·云原生
程序猿秃头之路35 分钟前
DDD 系列:聚合和聚合根详解
数据库·oracle·ddd·领域驱动设计
chatexcel1 小时前
不用写 SQL,如何用AI直连数据库生成可刷新的数据看板?ChatExcel的一种实践
大数据·数据库·人工智能·sql·数据分析·excel
码上上班1 小时前
Mongodb课程
数据库·mongodb
农村小镇哥2 小时前
Oracle中的锁和10704对高级队列锁
数据库·oracle
峥无2 小时前
SQL性能调优:从执行计划看懂索引的使用与失效
数据库·sql
xyj29175964112 小时前
在Trae中配置数据库MCP
数据库·ai·mcp