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、成果演示

相关推荐
做怪小疯子3 小时前
华为笔试0429
python·numpy
Warson_L3 小时前
Dictionary
python
Flying pigs~~5 小时前
RAG智慧问答项目
数据库·人工智能·缓存·微调·知识库·rag
misL NITL5 小时前
mysql之如何获知版本
数据库·mysql
许彰午5 小时前
CacheSQL(二):主从复制——OpLog 环形缓冲区与故障自动恢复
java·数据库·缓存
寒山李白5 小时前
解决 python-docx 生成的 Word 文档打开时弹出“无法读取内容“警告
python·word·wps·文档·docx·qoder
2401_832365526 小时前
JavaScript中rest参数(...args)取代arguments的优势
jvm·数据库·python
Sirius.z6 小时前
第J3周:DenseNet121算法详解
python
2301_779622417 小时前
Go语言怎么用信号量控制并发_Go语言semaphore信号量教程【入门】
jvm·数据库·python
2301_766283447 小时前
c++如何将控制台输出保存到文件_cout重定向到txt【详解】
jvm·数据库·python