Django中不使用forms.py实现内容访问前密码校验功能
Django实现通行码验证访问站点内容方案
1. 调整views.py逻辑
核心通过session存储用户验证状态,直接处理POST提交的密码,无需额外编写forms.py:
from django.shortcuts import render from .models import Text # Create your views here. def textview(request, slug): obj = Text.objects.get(slug=slug) context = { 'obj': obj, 'show_content': False, 'error_msg': '' } # 处理密码提交请求 if request.method == 'POST': input_pwd = request.POST.get('password', '') if input_pwd == obj.password: # 验证通过,写入session标记 request.session[f'auth_{slug}'] = True context['show_content'] = True else: context['error_msg'] = '通行码错误,请重试' # 非POST请求,检查是否已有验证标记 else: if request.session.get(f'auth_{slug}', False): context['show_content'] = True return render(request, 'text/textpage.html', context) def home(request): return render(request, 'text/index.html', {})
2. 编写text/textpage.html模板代码
同一个模板兼顾密码输入和内容展示,符合加载模板后先提示输入通行码的流程:
<!DOCTYPE html> <html> <head> <title>受保护的内容</title> </head> <body> {% if show_content %} <!-- 验证通过展示实际内容 --> <div> {{ obj.text }} </div> {% else %} <!-- 未验证展示通行码输入框 --> <div style="max-width: 400px; margin: 100px auto;"> <h3>请输入通行码访问内容</h3> {% if error_msg %} <p style="color: red;">{{ error_msg }}</p> {% endif %} <form method="post"> {% csrf_token %} <input type="password" name="password" placeholder="请输入通行码" required> <button type="submit">提交</button> </form> </div> {% endif %} </body> </html>
补充说明
- 当前方案中密码是明文存储在数据库中,生产环境建议使用Django内置的加密方法对密码进行哈希存储,避免数据泄露风险
- 如果需要设置验证有效期,可以在session存储时额外存入时间戳,验证时判断是否超过有效期即可
内容的提问来源于stack exchange,提问作者Vivek K. Singh
相关产品推荐
相关产品推荐

