基本实现
路由
from django.urls import path
from . import viewsapp_name = 'index'
urlpatterns = [path('', views.index, name='index'),path("login.html/", views.login, name="login"),
]
视图
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exemptdef 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跨站攻击。然后给出了用户名和密码的输入框,以及一个登录按钮。
<!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>
首页:这个页面非常简单,只需要展示自己是首页即可。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>