Python Django 登陆案例

发布时间 2023-03-22 21:09:06作者: 幻非

在根目录下新建一个 templates 文件

修改 settings.py 文件

image

image

templates 文件夹内新建一个 login.html 文件,并写入模板内容

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width,initial-scale=1" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>用户登陆</title>
    </head>
    <body>
        <form action="/login/" method="post">
            {% csrf_token %}
            <div>
                <span>用户名</span>
                <input type="text" name="name" />
            </div>
            <div>
                <span>密码</span>
                <input type="password" name="pwd" />
            </div>
            <input type="submit" value="登陆" />
        </form>
    </body>
</html>

修改 users 目录下的 views.py 文件

from django.http import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect


def index(request):
    return render(request, 'login.html')


def login(request):
    if request.method == 'GET':
        name = request.GET.get('name')
        pwd = request.GET.get('pwd')
        context = {name: name, pwd: pwd}
        print(str(context))
        return HttpResponse("拒绝访问")
    else:
        name = request.GET.get('name')
        pwd = request.GET.get('pwd')
        context = {name: name, pwd: pwd}
        print(str(context))
        return redirect('https://baidu.com')

修改 urls 文件夹

from django.contrib import admin
from django.urls import path
from users import views

urlpatterns = [
    path('index/', views.index),
    path('login/', views.login),
    path('admin/', admin.site.urls),
]

之后运行

python manage.py runserver

便可以通过 http://127.0.0.1:8000/index/ 访问

如果报 TemplateDoesNotExist 错误
image

请检查 templates 的位置

image