この前の記事(Google App EngineのDjangoヘルパーで認証してみる)からDjangoヘルパーを利用したApp Engine用のアプリをしこしこと作ってるのですが、もともとDjangoにうといもので、ソースコードを汗書いて読んだりしながら格闘している感じです。
そんな中で、Userモデルの get_profile というメソッドの使いどころがちょっと分からなかったので、調べたところをメモ。
django_appengine.auth.models
def get_profile(self):
"""
Returns site-specific profile for this user. Raises
SiteProfileNotAvailable if this site does not allow profiles.
When using the App Engine authentication framework, users are created
automatically.
"""
from django.contrib.auth.models import SiteProfileNotAvailable
if not hasattr(self, '_profile_cache'):
from django.conf import settings
if not hasattr(settings, "AUTH_PROFILE_MODULE"):
raise SiteProfileNotAvailable
try:
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
model = models.get_model(app_label, model_name)
self._profile_cache = model.all().filter("user =", self).get()
if not self._profile_cache:
raise model.DoesNotExist
except (ImportError, ImproperlyConfigured):
raise SiteProfileNotAvailable
return self._profile_cacheget_profileは名前のとおりユーザーと関連づけられたプロフィールを取得するためのメソッドです。
Djangoヘルパーを利用すると、初回ログイン時にUserモデルにユーザーのデータが自動で保存されますが、プロフィールを格納するモデルは用意されていません。
なので、プロフィール用のモデルを各自定義する必要があります。
from appengine_django.auth.models import User
class Profile(BaseModel):
user = db.ReferenceProperty(User) #Userモデルを参照
address = db.StringProperty() #住所
bio = db.TextProperty() #自己紹介
def __str__(self):
return self.user.usernameこんな感じで住所と自己紹介を保存するモデルを定義しました。
さらに、setting.pyに下のように記述
AUTH_PROFILE_MODULE = ‘app.Profile’ #app名.モデル名これでget_profileを使う準備ができました。
view.py
def index(request):
if request.user.is_authenticated():
try:
address = request.user.get_profile().address
bio = request.user.get_profile().bio
except DoesNotExist:
#ログインしていても
#プロフィールが登録されていないとDoesNotExistが飛んでくるプロフィールの作成や削除については特別なことはなにもないので割愛。
0 コメント:
コメントを投稿