Django 实现登录功能

基本实现

路由

python 复制代码
from django.urls import path
from . import views

app_name = 'index'
urlpatterns = [
    path('', views.index, name='index'),
    path("login.html/", views.login, name="login"),
]

视图

python 复制代码
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt


def index(request):
    return render(request, "index.html")


def login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == "zhangdapeng" and password == "zhangdapeng520":
            return redirect("index:index")
    return render(request, "login.html")

模板

登录页面:这个页面中,我们使用csrf生成一个隐藏输入框,这样Django会检测是否为CSRF跨站攻击。然后给出了用户名和密码的输入框,以及一个登录按钮。

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登录</h1>
<form action="{% url 'index:login' %}" method="post">
    {% csrf_token %}
    <div>
        <label for="username">账号</label>
        <input type="text" id="username" name="username">
    </div>
    <div>
        <label for="password">密码</label>
        <input type="password" id="password" name="password">
    </div>
    <div>
        <button type="submit">登录</button>
    </div>
</form>
</body>
</html>

首页:这个页面非常简单,只需要展示自己是首页即可。

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>
相关推荐
AI云海17 分钟前
python 列表、元组、集合和字典
开发语言·python
二十雨辰1 小时前
[爬虫]-Urllib
爬虫·python
玉鸯2 小时前
Agent Hook:在概率推理之上,为 Agent 叠加确定性控制
python·langchain·agent
weixin_446260853 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao3 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
qetfw4 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具
用户8356290780514 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
一次旅行5 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化
天天爱吃肉82185 小时前
【电源拆解:跟着问答逐一认识开关适配器PCB元器件】
大数据·人工智能·python·功能测试·嵌入式硬件·汽车