用Django创建主页和登录页面

你好。
我是Class Act基础设施事业部的大塚。

这次,我想在上次创建的基于anaconda的Django环境中添加主页和登录页面。
上篇文章如下所示。

 

目录文件结构

django-ページ1.drawio (1).png

环境构建

创建首页

首先,在qiita文件夹中,使用django-admin命令创建一个project。
这次我创建了一个名为testPJ的项目。

PS C:\Users\ohtsu\Documents\DjangoEnv\qiita> django-admin startproject testPJ
PS C:\Users\ohtsu\Documents\DjangoEnv\qiita> cd .\testPJ\
PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ> ls
    ディレクトリ: C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        2023/11/04     18:17                testPJ
-a----        2023/11/04     18:17            684 manage.py

在testPJ中创建一个名为templates的文件夹,并在其中再创建一个名为registration的文件夹。
如果像本次一样使用Django提供的登录模板,那么HTML文件默认会在registration文件夹中寻找。

PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ> mkdir templates
PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ> cd .\templates\
PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ\templates> mkdir registration

我想在这个时候暂时执行迁移。

PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ\templates> cd ..
PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ> python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

继续创建admin用户。

PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ> python manage.py createsuperuser
Username (leave blank to use 'ohtsu'): admin
Email address: admin@example.com
Password: 
Password (again): 
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

我们将编辑位于testPJ文件夹中的urls.py。

    • from .views import homeView

 

    • urls.pyと同じフォルダ上にあるviews.pyからhomeViewという処理を読み込む、みたいなイメージです。このviews.pyはこれから作成します。

 

    • path(“admin/”, admin.site.urls),

 

    • http://localhost:8000/admin

 

    • にアクセスすることでDjangoの管理画面にアクセスできるようにする設定です。

 

    • path(“”, homeView.as_view(), name=”home”),

 

    URLを指定しないでDjangoにアクセスしてくるとhomeViewの処理を行う。homeViewの処理はこれから記載します。
# this is project urls.py

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

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", homeView.as_view(), name="home"),
]

将创建一个views.py文件。

PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ> New-Item views.py

我将如下所示:
将TemplateView继承到homeView类中,
将home.html加载到template_name变量中。
这看起来可能有些困难,但我认为可以将其视为指定在访问时要显示的HTML文件。
我将在接下来创建home.html。

    • from django.views.generic import TemplateView

 

    djangoのライブラリからTemplateViewを呼び出しています。
# This is Project views.py

from django.views.generic import TemplateView

class homeView(TemplateView):
    template_name = "home.html"

创建一个名为home.html的文件在templates文件夹下。在这次的情况下,将按照以下方式进行a href的设置,即”{% url “应用名称” “在urls中指定的名称” %}”。这些内容稍后会再次出现。

<h1>Hello devProject</h1>

<a href="{% url 'admin:index' %}">ADMIN</a>

在settings.py的BASE_DIR中进行以下配置。

LANGUAGE_CODE = "ja"
TIME_ZONE = "Asia/Tokyo"
TEMPLATES = [
    {
        "DIRS": [BASE_DIR, "templates"],

我們將在這個狀態下運行服務器。

PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ> python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
November 04, 2023 - 20:05:41
Django version 4.1, using settings 'testPJ.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
image35.png

创建登录页面

我希望創建一個供非管理員使用而不是管理員使用的登錄界面。首先,我們將修改urls.py如下。

index_view = TemplateView.as_view(template_name=”index.html”)
path(“index/”, login_required(index_view), name=”index”),
http://localhost:8000/index
にアクセスしようとすると先にログインするように求めるようにしています。index.htmlはこれから作成していきます。

path(“auth/”, include(“django.contrib.auth.urls”), name=”login”),
http://localhost:8000/auth/login
にアクセスすると管理者以外のログイン画面が表示されます。
include(“django.contrib.auth.urls”)と書くことでDjangoが事前に用意しているログイン関連のライブラリを使用して簡単にログイン画面を作成できるようになるようです。なお、URLにはauth/loginと記載しており、一方でpathにはauth/としか記載しておりませんが、これはこのライブラリを使用する際の仕様のようです。

# This is Project urls.py

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from .views import homeView

index_view = TemplateView.as_view(template_name="index.html")

urlpatterns = [
    path('admin/', admin.site.urls),
    path("index/", login_required(index_view), name="index"),
    path("auth/", include("django.contrib.auth.urls"), name="login"),
    path('', homeView.as_view(), name="home"),
]

然后,在templates文件夹下的registration文件夹中创建login.html。
Django默认设置了登录相关的库在templates>registration中寻找templates文件。

PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ> cd .\templates\
PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ\templates> cd .\registration\
PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ\templates\registration> New-Item login.html
PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ\templates\registration> ls 
    ディレクトリ: C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ\templates\registration
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        2023/11/04     20:25              0 login.html

login.html的内容如下所示。

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}   
    <button type="submit">ログイン</button>

顺便说一下,在模板文件夹中创建一个 index.html 文件。

PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ\templates> New-Item index.html
PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ\templates> ls
    ディレクトリ: C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ\templates
Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        2023/11/04     20:25                registration
-a----        2023/11/04     20:13             72 home.html
-a----        2023/11/04     20:27              0 index.html

我已经将index.html的内容设定如下。

{% if user.is_authenticated %}
{{ user.username }}さん、こんにちは。
<a href="{% url 'logout' %}">ログアウト</a>
{% else %}
<p>ログインしていません</p>
{% endif %}

接下来,在settings.py的末尾添加以下的配置。使用在urls.py中设置的name来指定。

LOGIN_URL:
LOGIN_URL は、ログインが必要なページにアクセスしようとした際にリダイレクトされるログインページのURLを指定します。通常、この値はログインページのURLパターンの名前と一致する必要があります。たとえば、LOGIN_URL = “login” の場合、urls.py内で name=”login” という名前のログインページのURLパターンが定義されている必要があります。

LOGIN_REDIRECT_URL:
LOGIN_REDIRECT_URL は、ユーザーがログインに成功した場合にリダイレクトされるURLを指定します。ユーザーがログインした後、このURLにリダイレクトされます。たとえば、LOGIN_REDIRECT_URL = “index” の場合、ユーザーがログインした後に urls.py内で name=”index” という名前のページにリダイレクトされます。

LOGOUT_REDIRECT_URL:
LOGOUT_REDIRECT_URL は、ユーザーがログアウトした後にリダイレクトされるURLを指定します。ユーザーがログアウトした後、このURLにリダイレクトされます。たとえば、LOGOUT_REDIRECT_URL = “home” の場合、ユーザーがログアウトした後に urls.py内で name=”home” という名前のページにリダイレクトされます。

LOGIN_URL = "login"
LOGIN_REDIRECT_URL = "index"
LOGOUT_REDIRECT_URL = "home"

将home.html进行以下修改。

<h1>Hello devProject</h1>
<a href="{% url 'login' %}">ログイン</a>
<a href="{% url 'admin:index' %}">ADMIN</a>

开启服务器。

PS C:\Users\ohtsu\Documents\DjangoEnv\qiita\testPJ> python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
November 04, 2023 - 20:37:49
Django version 4.1, using settings 'testPJ.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
image40.png
bannerAds