[django | email] Build a Backend REST API - 9



Normalize email addresses


これは何ですか?
簡単に言えば、電子メールのドメイン名を小文字に統一するためです.
注意:https://stackoverflow.com/questions/27936705/what-does-it-mean-to-normalize-an-email-address
For email addresses, [email protected] and [email protected] are equivalent; the domain part is case-insensitive according to the RFC specs. Normalizing means providing a canonical representation, so that any two equivalent email strings normalize to the same thing.

The comments on the Django method explain:

Normalize the email address by lowercasing the domain part of it.

Share
Improve this answer
Follow

テストコードの作成


test_models.py
from django.test import TestCase
from django.contrib.auth import get_user_model


class ModelTests(TestCase):
    def test_create_user_with_email_successful(self):
        '''Test creating a new user with an email is successful'''
        email = '[email protected]'
        password = 'testpassword123'
        user = get_user_model().objects.create_user(
            email=email,
            password=password,
        )

        self.assertEqual(user.email, email)
        self.assertTrue(user.check_password(password))

    def test_new_user_email_normalized(self):
        """Test the email for a new user is normalized"""
        email = '[email protected]'
        user = get_user_model().objects.create_user(email, 'test123')
        self.assertEqual(user.email, email.lower())
def test_new_user_email_normalized(self):メソッドを書く
Email変数には、任意の文字列の電子メールが含まれます.
user = get_user_model().objects.create_user(email, password='test123')
カスタムManagerクラスメソッドcreate_user()を使用して、userオブジェクトを簡単に作成します.参考までに、少なくともpassword=\'test123\'、「test 123」と書くのはこんなに短いので、少なくとも機能的な操作は同じでしょう?!

ではテスト~!


manage.py test

失敗したナジョ?
user = get_user_model().objects.create user(email,password=「test 123」)#このソースコードは、モデルで作成されたオブジェクトの電子メールが大文字であることを検出します.

self.normalize_email()🎃


Eメールを標準化します.

既存
user = self.model(email=email, **extra_fields)
変更後
user = self.model(email=self.normalize_email(email), **extra_fields)
注意:https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#django.contrib.auth.models.BaseUserManager.normalize_email
テストをやり直すと成功します~