ほんじゃらねっと

ダイエット中プログラマのブログ

django-registrationでユーザー登録と同時にプロファイルを登録する。

django-registration
http://code.google.com/p/django-registration/


django-registrationはユーザー登録や認証関連の処理を一通り行ってくれる便利なdjangoアプリケーションである。
設置方法等については、下記のページに分かりやすい説明が記載されている。
http://d.hatena.ne.jp/jYoshiori/20070930/1191180980
http://takatoshi.g.hatena.ne.jp/nitsuji/20071021/1192953110


このアプリケーションに備わっている、プロファイル作成コールバック機能を使い、ユーザー登録時にこちらが独自に定義したユーザープロファイルオブジェクトを登録する処理を使用したので使用方法を記録しておく。


ここで言うプロファイルとは、djangoのユーザー情報に情報を付加できるクラスのことで、settings.pyで下記のように定義できる。

AUTH_PROFILE_MODULE = 'account.UserProfile'


こう定義しておくと、project_home/account/models.pyのUserProfileクラスオブジェクトを下記のようにユーザーオブジェクトから呼び出せるようになる。

user.get_profile()


詳細はこちら。
http://www.djangoproject.com/documentation/authentication/#storing-additional-information-about-users


下記のようなプロファイルクラスを定義した。
project_home/account/models.py

class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
comment = models.CharField("Profile Comments", max_length=255, blank=True, null=True)


user.get_profile()メソッドは関連するオブジェクトが存在しないとエラーを発生させるので、
ユーザー登録時にこのUserProfileクラスのオブジェクトを一緒に作成させる。
これをdjango-registrationで行う方法を調べたところ、まずはプロファイルを登録する処理を行う関数を定義しておく。この関数は引数にuserオブジェクトを受取るので、それを使って登録処理を定義する。


project_home/accounts/views.py

from project_home.account.models import UserProfile
def profile_callback(user):
profile = UserProfile()
profile.user = user
profile.save()


その後、下記のようにurls.pyに定義すると動作してくれるようだ。


project_home/urls.py

from django.conf.urls.defaults import *
from project_home.account.views import profile_callback
urlpatterns = patterns('',
url(r'^accounts/register/$', 'registration.views.register', {"profile_callback": profile_callback}, name="registration_register"),
(r'^accounts/', include('registration.urls')),
)


プロファイルを使用しない場合は、「accounts/」の定義だけで動作する。
上記に関する詳しい説明はdjango-registrationに付属のマニュアルに記載されている。