python(Django)之登录功能实现

1、创建登陆函数

复制代码
def login(request):
    if request.POST:
        username = password = ''
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            request.session['username'] = username
            response = HttpResponseRedirect('/home/')
            return response
        else:
            return render(request, 'login.html', {'error': 'username or password error'})
    return render(request, 'login.html')


def home(request):
    return render(request, 'home.html')

2、创建向导

复制代码
path('home/', views.home)

3、添加页面

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    <title>自动化测试平台</title>
</head>
<body>
<ul class = "nav navbar-nav navbar-right" >
    <li>欢迎,<a href="#">{{ user }}</a> </li>
    <li><a href="/logout/">退出</a> </li>
</ul>

</body>
</html>

4、优化前面的页面

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
    <title>login</title>
    <style>
        body{
            text-align: center;
        }
    </style>
</head>
<body>
<h1>自动化平台测试</h1>
<h1>login</h1>
<form method="post" action="/login/">{% csrf_token %}
    <br><a>&nbsp;&nbsp;用户名:</a>
    <input name="username" type="text" placeholder="test">
    <br><br><a>&nbsp;&nbsp;密&nbsp;&nbsp;码</a>
    <br><input name="password" type="password" placeholder="你的密码"><br>
    {{error}}<br>&nbsp;
    <br><button style="width: 220px;height: 28px" name ="submit" type="submit">登陆</button>

</form>
</body>
</html>

5、成果演示

相关推荐
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
IvorySQL1 天前
PostgreSQL 技术日报 (3月6日)|为什么 Ctrl-C 在 psql 里让人不安?
数据库·postgresql·开源
NineData1 天前
数据库管理工具NineData,一年进化成为数万+开发者的首选数据库工具?
运维·数据结构·数据库
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
IvorySQL1 天前
PostgreSQL 技术日报 (3月5日)|规划器控制力升级,内核能力再进阶
数据库·postgresql·开源
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm
数据组小组2 天前
免费数据库管理工具深度横评:NineData 社区版、Bytebase 社区版、Archery,2026 年开发者该选哪个?
数据库·测试·数据库管理工具·数据复制·迁移工具·ninedata社区版·naivicat平替