프레임워크/Django

Django로 카카오 소셜 로그인/회원가입 구현하기

개발자 지망생 리네 2025. 6. 3. 15:08

1. allAuth 사용

- 공식 문서를 참조하는 습관을 들이자.

https://docs.allauth.org/en/latest/

 

django-allauth

Toggle Light / Dark / Auto color theme Toggle table of contents sidebar

docs.allauth.org

 

- 기초 설정은 여기서 볼 수 있다.

https://docs.allauth.org/en/latest/installation/quickstart.html

 

Quickstart - django-allauth

Toggle Light / Dark / Auto color theme Toggle table of contents sidebar

docs.allauth.org

 

 

(1) 패키지 설치 (프로젝트 가상 환경 터미널)

pip install django-allauth

 

 

(2) settings.py에 아래 코드 추가

INSTALLED_APPS = [
	...

    # allauth (카카오 소셜 로그인)
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.kakao',
    'django.contrib.sites',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    # account middleware (카카오 소셜 로그인)
    'allauth.account.middleware.AccountMiddleware',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / "templates"],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
				...

                # allauth (카카오 소셜 로그인)
                'django.template.context_processors.request',
            ],
        },
    },
]

# 카카오 소셜 로그인
AUTHENTICATION_BACKENDS = [
    # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',

    # `allauth` specific authentication methods, such as login by email
    'allauth.account.auth_backends.AuthenticationBackend',
]

# 로그인 성공 후 반환 URL
LOGIN_REDIRECT_URL = '/'

 

 

(3) urls.py에 아래 코드 추가

from django.contrib import admin
from django.urls import path, include
from accounts.views import home

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),

    # 홈 화면
    path('', home, name='home'),
]

 

 

(4) kakao Developers에 앱 등록하기

- 카카오 회원가입/로그인이 어떻게 작동하는지를 확인한다

- 문서가 생각보다 친절하게 나와있어서 이해하기 어렵지는 않았다.

https://developers.kakao.com/docs/latest/ko/kakaologin/common 

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

 

- 앱을 등록하는 방법은 아래 블로그를 참고했다.

https://backendjun.tistory.com/13

 

[Django] Django-allauth로 Kakao Login, Logout 해보기

django-allauth란? 소셜 인증 정보를 처리하는 장고의 응용 프로그램입니다. 공유해야하는 정보에 대해 관리하는데 로그인, 로그아웃, 회원가입 등등 통합적인 기능을 간편하게 제공합니다. 아래는

backendjun.tistory.com

-> 다만 나는 심사 신청을 하지 않았기 때문에, 카카오계정 이메일 정보를 가져오는 것은 불가능했다.

 

(5) 관리자 사이트 설정

https://backendjun.tistory.com/13

 

[Django] Django-allauth로 Kakao Login, Logout 해보기

django-allauth란? 소셜 인증 정보를 처리하는 장고의 응용 프로그램입니다. 공유해야하는 정보에 대해 관리하는데 로그인, 로그아웃, 회원가입 등등 통합적인 기능을 간편하게 제공합니다. 아래는

backendjun.tistory.com

- 위에 올린 블로그를 참고했다.

 

- http://localhost:8000/accounts/kakao/login/ 으로 접속해 확인한다.

 

- 만일 Django adminstration에 SOCIAL APPLICATIONS가 없으면 아래 링크를 참고하자.

https://linae-developingstudy.tistory.com/47

 

[Django] Django adminstration 에 SOCIAL APPLICATIONS 가 없을 때

Django 관리자 페이지에 SOCIAL APPLICATIONS 가 없는 경우가 있다. SocialApplication, SocialAccount는 allauth.socialaccount 앱에서 제공하는 모델인데, 관리자에 등록이 되어 있지 않으면 보이지 않는다. 이럴 경우

linae-developingstudy.tistory.com

- requests라는 모듈을 찾을 수 없다는 에러가 뜨면 아래 링크를

https://linae-developingstudy.tistory.com/48

 

[Django] ModuleNotFoundError: No module named 'requests'

카카오 소셜 회원가입/로그인 중에 발생한 오류다. allauth를 사용하는데, Django-allauth가 내부에서 requests 라는 파이썬 라이브러리를 사용한다. 그러나 가상환경에 requests가 설치되어 있지 않아 발

linae-developingstudy.tistory.com

- Django adminstrations에 SITES가 없다면 아래 링크를 참고하자.

https://linae-developingstudy.tistory.com/49

 

[Django] Django adminstration 에 SITES가 없을 때

- INSTALLED_APPS에 django.contrib.sites를 넣자.- SITE_ID 값도 설정한다.SITE_ID = 1 - 저장 후 마이그레이션

linae-developingstudy.tistory.com

 

- 테이블이 존재하지 않는 경우를 두 가지 겪었는데, 해결 방법을 따로 적어놓았다.

https://linae-developingstudy.tistory.com/50

 

[Django] Table '프로젝트명.django_site' doesn't exist

- django.contrib.sites를 INSTALLED_APPS에 넣었는데 거기서 사용하는 django_site 테이블이 DB에 만들어지지 않았을 때 발생-> 해결 방법 : sites 앱만 마이그레이션 (아래 코드 추가)python manage.py migrate sites

linae-developingstudy.tistory.com

https://linae-developingstudy.tistory.com/52

 

[Django] Table '프로젝트명.socialaccount_socialapp_sites' doesn't exist

- SocialApplication과 Site 사이의 다대다 관계를 저장하는 테이블이 DB에 생성되지 않음-> migrate를 하려고 하였으나 해당 테이블이 이미 존재한다는 에러 메시지를 전달받음 원인- mysql DB에 일부 테이

linae-developingstudy.tistory.com

 

(6) login.html 수정

- 프로젝트 전체 폴더>templates>socialaccount>login.html에 html코드를 추가한다.

- 디자인마다 html 코드가 다르지만, 아래 코드는 꼭 넣어주도록 하자.

<form method="post" actions="">
   {% csrf_token %}
   {{ form.as_p }}
      <button class="kakao-btn">
         <img src="/static/socialaccount/kakao_login.png" alt="카카오 로그인" />
      </button>
</form>

 

실행 결과