【Django笔记】 登录功能

1. post请求

sign/templates/index.html

其中 :

复制代码
<form  method="post">
python 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<h1>  发布会管理
</h1>
<form  method="post">
    <input name="username" type="text" placeholder="username"><br>
    <input name="password" type="password" placeholder="password"><br>
    <button id="btn"  type="submit">登录</button>

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

2.出现跨站请求伪造

Django 正对CSRF 的保护错误是生成的每个表单中放置一个自动生成令牌。通过这个令牌胖墩POST请求是否来自同一个网站。form 添加 { % csrf_token %}

python 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>
<h1>  发布会管理
</h1>
<form  method="post">
    <input name="username" type="text" placeholder="username"><br>
    <input name="password" type="password" placeholder="password"><br>
    <button id="btn"  type="submit">登录</button>
  {%  csrf_token  %}
</form>
</body>
</html>

3.Cookie 和Session

Cookie 机制 :

Cookie 分发通过拓展Http 协议来实现,服务器通过在http 的响应头中加上一行特殊的指示来提示浏览器按照只是生成相应的Cookie.

Session机制: Session 机制 是一种服务器的机制,服务器使用一种雷士与散列表的结构,保存信息。

Cookie 使用

event_manage.html

python 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <h1> Login  Success  !</h1>
    <div style="float:right;">
    <a> 嘿 {{ user }} 欢迎 </a>
    </div>
</body>
</html>

4.Cookie

sign/views.py

设置cookie 的值

response= HttpResponseRedirect('/event_manage/') # 重定向
response.set_cookie('user',username,3600) # 添加浏览器
return response

# 发布会管理 --取出cookie 的值
def event_manage(request):
username=request.COOKIES.get("user","")# 读取浏览器cookie
return render(request, "event_manage.html",{"user":username})

python 复制代码
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.http import HttpResponse, HttpResponseRedirect


# 定义inex 函数,通过HttpResponse 类向客户端返回字符创
def index(request):
    # return HttpResponse("Hello Django!")  # 使用Django 的render函数
    return render(request, "index.html")


def login_action(request):
    if request.method == "POST":
        username = request.POST.get('username', "")  # 字段对应表单的input属性
        password = request.POST.get('password', '')
        if username == 'admin' and password == "admin123":

            # return HttpResponse('login success')
            response= HttpResponseRedirect('/event_manage/')  # 重定向
            response.set_cookie('user',username,3600)  # 添加浏览器
            return response
        else:
            return render(request, "index.html", {'error': 'username or password error!'})


# 发布会管理
def event_manage(request):
    username=request.COOKIES.get("user","")# 读取浏览器cookie
    return render(request, "event_manage.html",{"user":username})

5.Session

python 复制代码
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.http import HttpResponse, HttpResponseRedirect


# 定义inex 函数,通过HttpResponse 类向客户端返回字符创
def index(request):
    # return HttpResponse("Hello Django!")  # 使用Django 的render函数
    return render(request, "index.html")


def login_action(request):
    if request.method == "POST":
        username = request.POST.get('username', "")  # 字段对应表单的input属性
        password = request.POST.get('password', '')
        if username == 'admin' and password == "admin123":

            # return HttpResponse('login success')
            response= HttpResponseRedirect('/event_manage/')  # 重定向
            #response.set_cookie('user',username,3600)  # 添加浏览器
            request.session['user']=username # 将session 信息记录到浏览器
            return response
        else:
            return render(request, "index.html", {'error': 'username or password error!'})


# 发布会管理
def event_manage(request):
    #username=request.COOKIES.get("user","")# 读取浏览器cookie
    username=request.session.get("user","") # 读取浏览器session
    return render(request, "event_manage.html",{"user":username})
python 复制代码
   return super().execute(sql, params)
  File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\utils.py", line 80, in _execute
    with self.db.wrap_database_errors:
  File "D:\software\python3\anconda3\Lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_session
[01/Oct/2023 16:18:46] "POST /login_action/ HTTP/1.1" 500 140361

通过 migrate 命令进行数据迁移。

相关推荐
liliangcsdn19 分钟前
如何使用python创建和维护sqlite3数据库
数据库·sqlite
JJJJ_iii1 小时前
【机器学习01】监督学习、无监督学习、线性回归、代价函数
人工智能·笔记·python·学习·机器学习·jupyter·线性回归
TDengine (老段)7 小时前
TDengine 数学函数 DEGRESS 用户手册
大数据·数据库·sql·物联网·时序数据库·iot·tdengine
TDengine (老段)7 小时前
TDengine 数学函数 GREATEST 用户手册
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
安当加密7 小时前
云原生时代的数据库字段加密:在微服务与 Kubernetes 中实现合规与敏捷的统一
数据库·微服务·云原生
Larry_Yanan7 小时前
QML学习笔记(四十二)QML的MessageDialog
c++·笔记·qt·学习·ui
爱喝白开水a7 小时前
LangChain 基础系列之 Prompt 工程详解:从设计原理到实战模板_langchain prompt
开发语言·数据库·人工智能·python·langchain·prompt·知识图谱
想ai抽7 小时前
深入starrocks-多列联合统计一致性探查与策略(YY一下)
java·数据库·数据仓库
武子康7 小时前
Java-152 深入浅出 MongoDB 索引详解 从 MongoDB B-树 到 MySQL B+树 索引机制、数据结构与应用场景的全面对比分析
java·开发语言·数据库·sql·mongodb·性能优化·nosql
longgyy8 小时前
5 分钟用火山引擎 DeepSeek 调用大模型生成小红书文案
java·数据库·火山引擎