Hello one! This is Ponta, a Shiba Inu. It's hot today so I ate Gari-gari-kun soda flavor. It was insanely delicious! Gari-gari-kun is made by a company in Saitama prefecture. Ponta has never been to Saitama prefecture.
Well, today I will challenge the user management function.
First, create an account application.
terminal
(venv_dog) Ponta@shiba_app # python manage.py startapp accounts
After creating the application, register it in INSTALLED_APPS in shiba_app / settings.py. Ponta's INSTALLED_APPS looks like this:
shiba_app/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'top.apps.TopConfig',
'wan.apps.WanConfig',
'accounts.apps.AccountsConfig',
]
Last 'accounts.apps.AccountsConfig', Added.
Some settings are required in settings.py for user registration / authentication function. First, send and receive emails for email address authentication, which is displayed on the console in the development environment. The setting for this is EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' is.
Then, let Django reference your custom user model, AUTH_USER_MODEL = 'accounts.CustomUser' To set.
In addition, for django-allauth, described below, SITE_ID = 1 To set.
Also, the authentication backend settings AUTHENTICATION_BACKENDS = ( 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ) is. allauth.account.auth_backends.AuthenticationBackend Is an authentication backend for general users to log in with email address authentication, django.contrib.auth.backends.ModelBackend Is an authentication backend for superusers to log in to the admin site with their username.
ACCOUNT_AUTHENTICATION_METHOD = 'email' So, set it to email address authentication, ACCOUNT_USERNAME_REQUIRED = True Requires a user name.
ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_REQUIRED = True It is mandatory to confirm your e-mail address.
LOGIN_REDIRECT_URL = 'wan:index' After logging in with, redirect to the index of the wan application and ACCOUNT_LOGOUT_REDIRECT_URL = 'top:index' After logging out with, redirect to the index of the top application.
ACCOUNT_LOGOUT_ON_GET = True Is a setting to log out immediately after clicking the logout button.
shiba_app/settings.py
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
AUTH_USER_MODEL = 'accounts.CustomUser'
SITE_ID = 1
AUTHENTICATION_BACKENDS = (
'allauth.account.auth_backends.AuthenticationBackend',
'django.contrib.auth.backends.ModelBackend',
)
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = 'mandatory'
ACCOUNT_EMAIL_REQUIRED = True
LOGIN_REDIRECT_URL = 'wan:index'
ACCOUNT_LOGOUT_REDIRECT_URL = 'top:index'
ACCOUNT_LOGOUT_ON_GET = True
Django defines a default user model, but you can override it to define a custom user model.
account/models.py
rom django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
class Meta:
verbose_name_plural = 'CustomUser'
dogname = models.CharField(verbose_name='Dog Name', blank=False, max_length=40)
introduction = models.TextField(verbose_name='Introduction', blank=True)
I added dogname and introduction. I would like to make these input screens later if I have a chance.
terminal
(venv_dog) Ponta@shiba_app # python manage.py makemigrations
Migrations for 'accounts':
accounts/migrations/0001_initial.py
- Create model CustomUser
Process finished with exit code 0
(venv_dog) Ponta@shiba_app # python manage.py migrate
Operations to perform:
Apply all migrations: accounts, admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0001_initial... 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 accounts.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 sessions.0001_initial... OK
(venv_dog) Ponta@shiba_app #
Since it is troublesome to create a user authentication function, we will use a package called django-allauth.
terminal
(venv_dog) Ponta@shiba_app # pip install django-allauth
In INSTALLED_APPS in settings.py to make Django-allauth available to your application 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', Add 4 lines.
shiba_app/settings.py
INSTALLED_APPS = [
(Omission)
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
]
Run the migrate command again to create the table used by django-allauth.
terminal
(venv_dog) Ponta@shiba_app # python manage.py migrate
Operations to perform:
Apply all migrations: account, accounts, admin, auth, contenttypes, sessions, sites, socialaccount
Running migrations:
Applying account.0001_initial... OK
Applying account.0002_email_max_length... OK
Applying sites.0001_initial... OK
Applying sites.0002_alter_domain_unique... OK
Applying socialaccount.0001_initial... OK
Applying socialaccount.0002_token_max_lengths... OK
Applying socialaccount.0003_extra_data_default_dict... OK
Create a superuser to access Django's admin screen.
terminal
(venv_dog) Ponta@shiba_app # python manage.py createsuperuser
Username: ponta
Email address: [email protected]
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: N
Password:
Password (again):
Superuser created successfully.
Oops, password validation seems to get stuck if the password is too short or too easy. The second time I set it seriously.
Now that you've created a superuser, try logging in to the Django admin screen. http://127.0.0.1:8000/admin/ To access. Then http://127.0.0.1:8000/admin/login/?next=/admin/ I was redirected to and the login screen appeared.
Enter the Username and Password you used to create the superuser here to log in. Then, I was able to log in successfully as shown below, and the management screen appeared.
Currently, three applications (top, wan, accounts) have been created in shiba_app.
shiba_app/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('top.urls')),
path('wan/', include('wan.urls')),
path('accounts/', include('allauth.urls')),
]
top/urls.py
from django.urls import path
from . import views
app_name = 'top'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
]
wan/urls.py
from django.urls import path
from . import views
app_name = 'wan'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
]
top/views.py
from django.views import generic
class IndexView(generic.TemplateView):
template_name = "top/index.html"
wan/views.py
from django.views import generic
class IndexView(generic.TemplateView):
template_name = "wan/index.html"
The user name and logout button are displayed during login, and the user registration button and login button are displayed during logout.
top/templates/top/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Shiba Inu Ponta's "What is a dog?"</title>
</head>
<body>
<h1>Shiba Inu Ponta's "What is a dog?"</h1>
<p>This is Ponta, a Shiba Inu. Regards One!</p>
{% if user.is_authenticated %}
<p>username:{{ user }}</p>
<p><a href="{% url 'account_logout' %}">Log out</a> </p>
{% else %}
<p><a href="{% url 'account_signup' %}">user registration</a></p>
<p><a href="{% url 'account_login' %}">Login</a></p>
{% endif %}
</body>
</html>
The user name and logout button are displayed during login, and the user registration button and login button are displayed during logout. (Eh! Same as before ??)
wan/templates/wan/index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Shiba Inu Ponta's "What is a dog?"</title>
</head>
<body>
<h1>Shiba Inu Ponta's "What is a dog?"</h1>
{% if user.is_authenticated %}
<p>username:{{ user }}</p>
<p><a href="{% url 'account_logout' %}">Log out</a> </p>
{% else %}
<p><a href="{% url 'account_signup' %}">user registration</a></p>
<p><a href="{% url 'account_login' %}">Login</a></p>
{% endif %}
</body>
</html>
Now, let's check the top page.
Click User Registration.
Register a user for testing.
An email has been sent. Since it is a test now, an email message will be sent to the console (terminal screen).
terminal
[30/Aug/2020 11:45:57] "GET /accounts/signup/ HTTP/1.1" 200 1330
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: [example.com] Please Confirm Your E-mail Address
From: webmaster@localhost
To: [email protected]
Date: Sun, 30 Aug 2020 11:46:30 -0000
Message-ID: (abridgement)
Hello from example.com!
You're receiving this e-mail because user Lisa has given yours as an e-mail address to connect their account.
To confirm this is correct, go to http://127.0.0.1:8000/accounts/confirm-email/NA:1kCLn4:g2Po76yr88dimfzO641FunQcGbYPexyYkTE4j0JLZ4Q/
Thank you from example.com!
example.com
-------------------------------------------------------------------------------
[30/Aug/2020 11:46:30] "POST /accounts/signup/ HTTP/1.1" 302 0
In the middle of this display, "http://127.0.0.1:8000/accounts/confirm-email/NA:1kCLn4:g2Po76yr88dimfzO641FunQcGbYPexyYkTE4j0JLZ4Q/" Email authentication is completed when you access.
Let's log in after email verification is completed.
After logging in, the following screen will appear.
When you log out, you will return to the first screen.
That's it. See you dear! one!
Recommended Posts