ここではユーザが自身のプロフィールを更新する機能を実装する.具体的にはとりあえず氏名(first_name, last_name)を更新できるようにする.まず,URL を定義します.
users/urls.py
from django.urls import path
from . import views
app_name = 'users'
urlpatterns = [
path('', views.users_index, name='index'),
path('<int:user_id>/', views.users_profile, name='profile'),
path('<int:user_id>/update/', views.users_update, name='update'),
path('login/', views.LoginView.as_view(), name='login'),
path('logout/', views.LogoutView.as_view(), name='logout'),
]
次にフォームを設計します.
users/forms.py
import unicodedata
from django import forms
from django.contrib.auth import authenticate, get_user_model, password_validation
from django.contrib.auth.hashers import UNUSABLE_PASSWORD_PREFIX, identify_hasher
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ValidationError
from django.core.mail import EmailMultiAlternatives
from django.template import loader
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.utils.text import capfirst
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
UserModel = get_user_model()
class UserForm(forms.ModelForm):
class Meta:
model = UserModel
fields = ('first_name', 'last_name')
widgets = {
'first_name': forms.TextInput(attrs={
'class': 'form-control',
'required' : True
}),
'last_name': forms.TextInput(attrs={
'class': 'form-control',
'required' : True
}),
}
labels = {
'first_name': 'First Name',
'last_name': 'Last Name',
}
def clean(self):
data = super().clean()
first_name = data.get('first_name')
last_name = data.get('last_name')
if len(first_name) == 0:
msg = "First Name が入力されていません"
self.add_error('first_name', msg)
elif len(first_name) > 20:
msg = "First Name の最大文字数は20文字です"
self.add_error('first_name', msg)
if len(last_name) == 0:
msg = "Last Name が入力されていません"
self.add_error('last_name', msg)
elif len(last_name) > 20:
msg = "Last Name の最大文字数は20文字です"
さらに view を定義します.
users/views.py
from urllib.parse import urlparse, urlunparse
from django.conf import settings
# Avoid shadowing the login() and logout() views below.
from django.contrib.auth import REDIRECT_FIELD_NAME, get_user_model
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
# from django.contrib.auth.forms import (
# AuthenticationForm,
# PasswordChangeForm,
# PasswordResetForm,
# SetPasswordForm,
# )
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.http import HttpResponseRedirect, QueryDict
from django.shortcuts import resolve_url
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.utils.http import url_has_allowed_host_and_scheme, urlsafe_base64_decode
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.debug import sensitive_post_parameters
from django.views.generic.base import TemplateView
from django.views.generic.edit import FormView
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.urls import reverse
from django.contrib import messages
# from django.shortcuts import redirect
# from django.urls import reverse
from .forms import UserForm
from .forms import AuthenticationForm
UserModel = get_user_model()
# Create your views here.
@login_required(login_url='/users/login/')
def users_index(request):
# if not request.user.is_authenticated:
# return redirect('%s?next=%s' % (reverse('users:login'), request.path))
context = {}
context['usermodels'] = UserModel.objects.all()
return render(request, 'users/index.html', context)
@login_required(login_url='/users/login/')
def users_profile(request, user_id):
context = {}
usermodel = get_object_or_404(UserModel, pk=user_id)
context['usermodel'] = usermodel
return render(request, 'users/profile.html', context)
@login_required(login_url='/users/login/')
def users_update(request, user_id):
if not request.user.is_authenticated:
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
if user_id != request.user.id:
# messages.success(request, '他ユーザのProfileは編集できません')
return redirect(reverse('comments:index'))
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
user = request.user
user.first_name = form.cleaned_data.get('first_name')
user.last_name = form.cleaned_data.get('last_name')
user.save()
messages.success(request, '更新しました')
return redirect(reverse('users:index'))
else:
context = {}
context['form'] = form
return render(request, 'users/profile_form.html', context)
else:
context = {}
context['user'] = request.user
context['user_id'] = user_id
context['form'] = UserForm(
initial={
'first_name' : request.user.first_name,
'last_name' : request.user.last_name,
}
)
return render(request, 'users/profile_form.html', context)
HTML ファイルを作成します.
users/templates/users/profile_form.html
{% extends "base.html" %}
{% block title %}
Update Profile
{% endblock %}
{% block content %}
<h1 class="my-5">コメントアプリケーション</h1>
<div class="card">
<div class="card-header">名前の変更</div>
<div class="card-body">
{% if form.errors %}
<p class="errornote">
次のエラーがありました.
</p>
{% endif %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary btn-block">
プロフィールの変更
</button>
</form>
</div>
<div class="card-footer">
<p>
</p>
</div>
</div>
{% endblock content %}
さらに Navbar にプロフィール変更ページへのリンクを設置するとともに,フラッシュメッセージを表示するためにテンプレートに要素を追加します.
comments/templates/base.html
{% load static %}<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}{% endblock %}</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body>
<div class="container">
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="/">Navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/comments">Comments</a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="/users/">Users</a>
</li>
</ul>
{% if user.is_authenticated %}
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
{{ user.username }}
</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="{% url 'users:profile' user.id %}">Profile</a></li>
<li><a class="dropdown-item" href="{% url 'users:update' user.id %}">Edit Profile</a></li>
<li><a class="dropdown-item" href="#">Action</a></li>
<li><a class="dropdown-item" href="#">Another action</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="{% url 'users:logout' %}">ログアウト</a></li>
</ul>
</li>
</ul>
{% else %}
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="{% url 'users:index' %}">Login</a>
</li>
</ul>
{% endif %}
</div>
</div>
</nav>
<div>
{% for message in messages %}
<p class="flash_message" onclick="this.classList.add('hidden')"> {{ message }}</p>
{% endfor %}
</div>
{% block content %}
{% endblock content %}
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
</body>
</html>
最後に,フォルダを作成してスタイルシートを設置します.
comments/static/css/style.css
/* フラッシュメッセージ */
.flash_message {
padding-top: 10px;
padding-bottom: 10px;
text-align: center;
color: #ffc;
background: #417690;
}
.hidden {
display: none;
}
スタイルシートの変更を有効にするために,Web サーバを再起動してください.
(py39) C:\Users\lecture\Documents\django\custom_auth_project>python manage.py runserver ⏎
Watching for file changes with StatReloader
Performing system checks...
Navbar の「Edit Profile」から名前の変更ページへ移動できます.
まだ登録されていなかった名前を入力して「プロフィールの変更」ボタンをクリックします.
更新すると Navbar 直下にフラッシュメッセージが表示できました.フラッシュメッセージをクリックして消去できることも確認してください.具体的には,フラッシュメッセージをクリックすると hidden
クラスが追加されるので,表示が消える仕組みになっています.
プロフィールページから First Name と Last Name が設定されていることを確認できます.