1、编写函数视图,判定用户名密码,验证通过进入home主页,不通过返回登录页面
def login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') print(username) print(password) user = authenticate(request, username=username, password=password) if user is not None: print(user) login(request, user) return redirect('home') else: error_message = 'Invalid username or password' return render(request, 'login.html', {'error_message': error_message}) else: return render(request, 'login.html')
2、创建路由
from django.urls import path from . import views urlpatterns = [ path('login/', views.login_view, name='login'),
]
3、前端模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login Window</title> <!-- 引入 Bootstrap 和 jQuery --> <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.2/css/bootstrap.min.css"> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.2/js/bootstrap.min.js"></script> <style> /* 将登录窗口置于页面中心位置 */ .login-wrapper { display: flex; justify-content: center; align-items: center; height: 100vh; } /* 登录窗口样式 */ .login { width: 300px; padding: 20px; border: 1px solid #ccc; border-radius: 5px; } .form-group { margin-bottom: 10px; } label { display: block; margin-bottom: 5px; } input[type="text"], input[type="password"] { width: 100%; padding: 5px; border: 1px solid #ccc; border-radius: 3px; } button { display: block; width: 100%; padding: 5px; margin-top: 10px; background-color: #007bff; color: #fff; border: none; border-radius: 3px; cursor: pointer; } button:hover { background-color: #0069d9; } </style> </head> <body> <div class="login-wrapper"> <div class="login"> <h2>登录</h2> <hr> {% if error_message %} <div class="alert alert-danger">{{ error_message }}</div> {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <div class="form-group"> <label for="username">用户名</label> <input type="text" id="username" name="username" placeholder="Enter your username"> </div> <div class="form-group"> <label for="password">密码</label> <input type="password" id="password" name="password" placeholder="Enter your password"> </div> <button type="submit">确认</button> </form> </div> </div> </body> </html>
标签:username,进阶,Django4,18,request,login,password,border,message From: https://www.cnblogs.com/beichengshiqiao/p/17355637.html