[PYTHON] What is a dog? Django--Create a custom user model

Added user registration / login / logout functions

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.

Create account app

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.

Other settings in shiba_app / setting.py

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

Defining a custom user model

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.

migration

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 # 

Install django-allauth

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',
]

Migrate again

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 superuser

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.

Log in to the management screen

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.

スクリーンショット 2020-08-30 18.22.33.png

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.

スクリーンショット 2020-08-30 18.22.55.png

Routing settings shiba_app / urls.py

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')),
]

Routing settings top / urls.py

top/urls.py


from django.urls import path
from . import views

app_name = 'top'

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
]

Routing settings wan / urls.py

wan/urls.py


from django.urls import path
from . import views

app_name = 'wan'

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
]

Screen settings top / views.py

top/views.py


from django.views import generic


class IndexView(generic.TemplateView):
    template_name = "top/index.html"

Screen settings wan / views.py

wan/views.py


from django.views import generic


class IndexView(generic.TemplateView):
    template_name = "wan/index.html"

Screen template top / 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>

Screen template 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. (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>

User registration test

Now, let's check the top page.

スクリーンショット 2020-08-30 21.59.52.png

Click User Registration. スクリーンショット 2020-08-30 20.46.29.png

Register a user for testing. スクリーンショット 2020-08-30 20.46.38.png

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.

スクリーンショット 2020-08-30 20.55.21.png

Let's log in after email verification is completed.

スクリーンショット 2020-08-30 20.56.59.png

After logging in, the following screen will appear.

スクリーンショット 2020-08-30 20.57.53.png

When you log out, you will return to the first screen.

スクリーンショット 2020-08-30 21.59.52.png

That's it. See you dear! one!

Recommended Posts

What is a dog? Django--Create a custom user model
What is a dog? Django--Create a custom user model 2
What is a super user?
User is not added successfully after creating a custom User model
What is a dog? Django installation volume
What is a dog? Python installation volume
Implement a Custom User Model in Django
What is a distribution?
What is a dog? Challenge Django templates! Volume
What is a terminal?
What is a hacker?
What is a pointer?
What is a dog? POST Sending Volume Using Django--forms.py
What is a dog? Django App Creation Start Volume--startapp
What is a dog? Django App Creation Start Volume--startproject
What is a decision tree?
What is a Context Switch?
What is a system call
[Definition] What is a framework?
What is a callback function?
What is a python map?
[Python] What is a zip function?
[Python] What is a with statement?
What is a lexical scope / dynamic scope?
What is a Convolutional Neural Network?
[My note] Django's custom User model
What is a dog? Volume of GET request and query parameters
What is a dog? Django--Get Name and Date from URL Volume
What is on_delete used in django's model?
It's a Mac. What is the Linux command Linux?
Tell me what a conformal map is, Python!
What is namespace
What is copy.copy ()
What is Django? .. ..
What is dotenv?
What is POSIX?
What is a dog? Django--Volume of using values obtained from URLs in class-based views
What is Linux
What is klass?
What is SALOME?
What is Linux?
What is python
What is hyperopt?
What is Linux
What is pyvenv
What is __call__
What is Linux
What is Python
Basics of Python learning ~ What is a string literal? ~
What is a recommend engine? Summary of the types
What is God? Make a simple chatbot with python
To myself as a Django beginner (2) --What is MTV?
What is a dog? Django--Getting Started with Form for the First Time POST Transmission Volume