使用Django实现带有用户认证的Hello World
这是一个带有用户认证的”Hello World”。我们将使用MariaDB作为数据库。
完成时的文件夹结构如下所示。
proj01
├── accounts
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── home
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── manage.py
├── proj01
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── templates
└── registration
├── base.html
├── logged_out.html
└── login.html
创建项目
django-admin startproject proj01
cd proj01/
python manage.py migrate
python manage.py startapp home
我会在这个时间点上运行开发服务器。
gunicorn proj01.wsgi
在浏览器中访问http://127.0.0.1:8000/。
创建要显示的页面
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
# @login_required
def index(request):
str_out = ""
str_out += "<p>*** home *** start ***</p>"
str_out += "<p>ホームです。</p>"
str_out += '<p><a href="accounts/logout/">Logout</a></p>'
str_out += "<p>*** Nov/09/2021 AM 08:38 ***</p>"
str_out += "<p>*** home *** end ***</p>"
return HttpResponse(str_out)
(省略)
INSTALLED_APPS = [
'home',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
(省略)
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
(省略)
from django.contrib import admin
from django.urls import include
from django.urls import path
urlpatterns = [
# path('accounts/', include('django.contrib.auth.urls')),
path('', include('home.urls')),
path('admin/', admin.site.urls),
]
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
我将再次启动服务器。
gunicorn proj01.wsgi
将数据库切换至MariaDB
(省略)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'tiger123',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
(省略)
反映設定更改
python manage.py migrate
创建超级用户
$ python manage.py createsuperuser
ユーザー名 (leave blank to use 'uchida'): admin
メールアドレス: test@test.com
Password:
Password (again):
我們將再次啟動伺服器。
gunicorn proj01.wsgi
你可以通过以下的方式来确认已创建的用户。
$ python manage.py dbshell
MariaDB [django]> select username from auth_user;
+----------+
| username |
+----------+
| admin |
| betty |
| jack |
| scott |
+----------+
4 rows in set (0.000 sec)
创建登录页面
创建模板
创建文件夹
mkdir templates
mkdir templates/registration
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Django System</title>
</head>
<body>
<div class="container">
<div class="content">
{% block content %}{% endblock %}
</div>
</div>
</body>
</html>
{% extends 'registration/base.html' %}
{% block title %}Login{% endblock %}
{% block content %}
<h1>Login</h1>
<section class="common-form">
{% if form.errors %}
<p class="error-msg">Your username and password didn't match. Please try again.</p>
{% endif %}
{% if next %}
{% if user.is_authenticated %}
<p class="error-msg">Your account doesn't have access to this page. To proceed,
please login with an account that has access.</p>
{% else %}
<p class="error-msg">Please login to see this page.</p>
{% endif %}
{% endif %}
<form method="post" action="{% url 'login' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="submit">Login</button>
<input type="hidden" name="next" value="{{ next }}"/>
</form>
</section>
{% endblock %}
{% extends 'registration/base.html' %}
{% block title %}Logout{% endblock %}
{% block content %}
<h1>Logged Out</h1>
<p>Thanks for spending some quality time with the Web site today.</p>
<p><a href="{% url 'login' %}">Log in again</a></p>
{% endblock %}
我会修改home/view.py。
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
@login_required
def index(request):
str_out = ""
str_out += "<p>*** home *** start ***</p>"
str_out += "<p>ホームです。</p>"
str_out += '<p><a href="accounts/logout/">Logout</a></p>'
str_out += "<p>*** Nov/09/2021 AM 08:38 ***</p>"
str_out += "<p>*** home *** end ***</p>"
return HttpResponse(str_out)
创建一个名为”accounts”的应用程序。
python manage.py startapp accounts
请修改proj01/urls.py文件。
from django.contrib import admin
from django.urls import include
from django.urls import path
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls')),
path('', include('home.urls')),
path('admin/', admin.site.urls),
]
实现退出登录。
(省略)
LOGIN_REDIRECT_URL = '/'
我将再次启动服务器。
gunicorn proj01.wsgi
登录用户应使用在http://127.0.0.1:8000/admin/注册的信息。