【Djangoメモ】ログイン機能

1.投稿リクエスト 

サイン/テンプレート/index.html

で: 

<フォームメソッド="ポスト">
<!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. クロスサイトリクエストフォージェリが発生する 

 CSRF エラーに対する Django の保護は、生成されたすべてのフォームに自動生成されたトークンを配置することです。このトークンを渡すと、POST リクエストが同じ Web サイトからのものであるかどうかが判断されます。フォーム追加 { % csrf_token %}

<!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とセッション 

クッキーの仕組み: 

Cookie の配布は HTTP プロトコルを拡張することで実現され、サーバーは http 応答ヘッダーに特別な命令行を追加することで、ブラウザーに対応する Cookie を生成するように要求します。 

セッション メカニズム: セッション メカニズムはサーバー メカニズムであり、サーバーは NVC とハッシュ テーブル構造を使用して情報を保存します。

クッキーの使用状況

イベント管理.html

<!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.クッキー

サイン/views.py

Cookieの値を設定する

response= HttpResponseRedirect('/event_manage/') # リダイレクト
            response.set_cookie('user',username,3600) # ブラウザーの
            応答を追加

# 会議管理 - Cookie の値を取得します
defevent_manage(request):
    username=request.COOKIES.get("user","")# ブラウザの Cookie を読み取ります
    return render(request, "event_manage.html",{" user" :ユーザー名}) 

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.セッション 

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})

   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

 

 データを移行するには、merge コマンドを使用します。

 

 

おすすめ

転載: blog.csdn.net/oDianZi1234567/article/details/133459066