Django 远程主机管理系统 - 登陆界面教程
以下是一个简单的 Django 远程主机管理系统的登陆界面的示例代码:
首先,创建一个名为 'remote_host_management' 的 Django 项目:
$ django-admin startproject remote_host_management
然后,创建一个名为 'accounts' 的 Django 应用:
$ cd remote_host_management
$ django-admin startapp accounts
在 'remote_host_management/remote_host_management/settings.py' 文件中,将 'accounts' 应用添加到 INSTALLED_APPS 列表中:
INSTALLED_APPS = [
...
'accounts',
...
]
在 'remote_host_management/remote_host_management/urls.py' 文件中,添加一个 URL 路由:
from django.urls import path, include
urlpatterns = [
...
path('accounts/', include('accounts.urls')),
...
]
在 'remote_host_management/accounts' 目录中,创建一个名为 'urls.py' 的文件,并添加以下代码:
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
path('login/', views.login_view, name='login'),
]
在 'remote_host_management/accounts' 目录中,创建一个名为 'views.py' 的文件,并添加以下代码:
from django.shortcuts import render
from django.contrib.auth import authenticate, login
def login_view(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return render(request, 'accounts/home.html')
else:
return render(request, 'accounts/login.html', {'error': 'Invalid credentials'})
else:
return render(request, 'accounts/login.html')
在 'remote_host_management/accounts/templates/accounts' 目录中,创建一个名为 'login.html' 的 HTML 模板文件,并添加以下代码:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
{% if error %}
<p style='color: red;'>{{ error }}</p>
{% endif %}
<form method='POST' action='{% url 'accounts:login' %}'>
{% csrf_token %}
<label for='username'>Username:</label>
<input type='text' id='username' name='username' required><br><br>
<label for='password'>Password:</label>
<input type='password' id='password' name='password' required><br><br>
<input type='submit' value='Login'>
</form>
</body>
</html>
在 'remote_host_management/accounts/templates/accounts' 目录中,创建一个名为 'home.html' 的 HTML 模板文件,并添加以下代码:
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h2>Welcome, {{ user.username }}!</h2>
<p>You are logged in.</p>
</body>
</html>
最后,运行开发服务器:
$ python manage.py runserver
现在,您可以通过访问 'http://localhost:8000/accounts/login/' 来查看登陆界面。输入正确的用户名和密码后,将显示 'home.html' 模板文件中的欢迎消息。
原文地址: https://www.cveoy.top/t/topic/p16S 著作权归作者所有。请勿转载和采集!