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>
相关推荐
白山编程大哥1 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
昭昭日月明2 小时前
RAGFlow 入门,不用从零造轮子
python·ai编程
莓有烦恼吖3 小时前
Vibe Coding 的一些思考
python
小白学大数据3 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
爱丶不疚3 小时前
写给前端工程师的现代 Python 工程化最佳实践:从 pnpm 到 uv,从 CommonJS 到 src-layout
javascript·python·typescript
2601_962297253 小时前
C# vs Java vs Python:YOLO工业部署性能对比实战
java·python·c·工业视觉·性能对比
CTA终结者4 小时前
示例、拆解和练习,要连成一条量化补课线
人工智能·python
lolijiaqi154 小时前
一线观察:长期体验后发现的医疗器械 CDMO 底层现象
大数据·python
spencer_tseng4 小时前
[j2cache ehcache.xml]/tmp/.ehcache-diskstore.lock (Permission denied)
xml·linux·python·ehcache·[j2cache
梦想不只是梦与想5 小时前
Python Web 框架:FastAPI
python·fastapi·web框架