0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Djangoでログイン時やサインアップ時に特定の処理をする

Posted at

概要

シグナルハンドラの作成

  • シグナルを受け取った時の処理を記述するための accounts/signals.py ファイルを作成します
from django.contrib.auth.signals import user_logged_in
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from config.google_analytics import send_ga4_event

User = get_user_model()

@receiver(user_logged_in)
def user_logged_in_handler(sender, request, user, **kwargs):
    # GA4イベントを送信
    client_id = request.session.session_key
    event_name = "user_login"
    params = {
        "user_id": user.id,
        "username": user.username,
    }
    send_ga4_event(client_id, event_name, params)

@receiver(post_save, sender=User)
def user_created_handler(sender, instance, created, **kwargs):
    if created:
        # GA4イベントを送信
        client_id = instance.id  # 新規ユーザーの場合、session_keyがないのでuser.idを使用
        event_name = "user_signup"
        params = {
            "user_id": instance.id,
            "username": instance.username,
        }
        send_ga4_event(client_id, event_name, params)

シグナルハンドラの読み込み

  • accounts/apps.py を修正して、シグナルハンドラを読み込みます
from django.apps import AppConfig

class AccountsConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'accounts'

    def ready(self):
        import accounts.signals  # シグナルを読み込む

INSTALLED_APPS の確認

  • プロジェクトのsettings.pyファイルで、 INSTALLED_APPSにaccountsが含まれているのを確認します
    • accountsが含まれているのに、追加で「"accounts.apps.AccountsConfig",」のように書くと、ユニークな名前ではないとエラーになります

Google Analyticsで動作確認

  • Google Analyticsの「リアルタイム」などで動作確認します

参考リンク

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?