1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

「超簡単」Djangoでログインページの実装

Posted at

django初心者ですが、手軽に実装できました。(セキュリティ面は考慮なし)
中身の理解がスカスカでも実装はできる。

手順として、下記ぐらいだったと思います。

  1. プロジェクトの作成
  2. アプリの作成
  3. setting ファイルの更新
  4. templatesディレクトリの作成
  5. ログイン、ログイン後のHTMLの作成
  6. viewの実装
  7. urlのパスを記述
  8. formの実装
  9. 開発サーバーの立ち上げ

開発環境
MacOS m1 Max 16

terminal

$ django-admin startproject <project_name>
$ cd <project_name>
$ python3 manage.py startapp <app_name>
$ python3 manage.py createsuperuser

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'login_app', # ここ追加
]

LANGUAGE_CODE = 'ja'

TIME_ZONE = 'Asia/Tokyo'

# login, logout redirect url 追加
LOGIN_URL = 'login_app:login'
LOGIN_REDIRECT_URL = 'login_app:home'
LOGOUT_REDIRECT_URL = 'login_app:login'

project_name/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("login_app.urls")),
]

templates/login_app/base.html

<!doctype html>
<html lang="ja">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>{% block title %}{% endblock %}</title>
</head>

<body>

    {% block content %}
    {% endblock %}
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous">
    </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous">
    </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous">
    </script>
</body>

</html>

login.html

{% extends "login_app/base.html" %}
{% block title %}Django Auth Function{% endblock %}

{% block content %}
<div class="container">
    <h1>Login</h1>
    <form action="" method="POST">
        <!--csrf_tokenは正規の通信かどうかを識別するための文字コード。-->
        {% csrf_token %}
        {{ form.non_field_errors }}
        {% for field in form %}
            {{ field.label }}
            <br>
            {{ field }}
            <br>
            {{ field.error }}
        {% endfor %}
        <br>
        <button type="submit">Login</button>
    </form>
</div>
{% endblock %}

home.html

{% extends 'login_app/base.html' %}

{% block title %}Home{% endblock %}

{% block content %}

{% if user.is_authenticated %}
  Hi {{ user.username }}!
  <a href="{% url 'login_app:logout' %}">ログアウト</a>
{% else %}
  <p>You are not logged in</p>
  <a href="{% url 'login' %}">login</a>
{% endif %}

{% endblock %}

view.py

from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView
from . import forms

class LoginView(LoginView):
    form_class = forms.LoginForm
    template_name = 'login_app/login.html'

class HomeView(LoginRequiredMixin, TemplateView):
    template_name = 'login_app/home.html'

class LogoutView(LoginRequiredMixin, LogoutView):
    template_name = 'login_app/login.html'

app_name/urls.py

from django.urls import path
from . import views

app_name="login_app"

urlpatterns = [
    path("login/", views.LoginView.as_view(), name="login"),
    path("home/", views.HomeView.as_view(), name="home"),
    path("logout/", views.LogoutView.as_view(), name="logout"),
]

forms.py

from django.contrib.auth.forms import AuthenticationForm

# ログインフォームを作成している。
class LoginForm(AuthenticationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs["class"] = "form-control"

terminal

$ python3 manage.py runserver

こちらかなり参考にさせていただきました。ありがとうございます。
https://qiita.com/onishi_820/items/c69ebb6a4e34da0f34d4

今回のProjectを自分のgithubにも上げています。
https://github.com/Yuji-Sakata0110/django_login_sample_20220927

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?