ドキュメントに従って、モデルにUserProfileテーブルを設定し、それを管理領域のUserテーブルに関連付けて、ユーザーが登録するときにこのUserProfileテーブルにユーザーに関する追加情報を保存しようとしています。
私は以下views.py
を持っています:
from django.contrib.auth import authenticate, login, logout
def register(request):
if request.method == 'POST':
query_dict = request.POST
username = query_dict.__getitem__("username")
email = query_dict.__getitem__("user_email")
password = query_dict.__getitem__("password")
repeat_password = query_dict.__getitem__("repeat_password")
role = query_dict.__getitem__("role")
user = User.objects.create_user(username, email, password)
# django.db.models.signals.post_save gets called here and creates the UserProfile
# I can write something like user_profile = user.get_profile() but I don't
# know how to save information to the profile.
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return HttpResponseRedirect("/")
上記のコードのコメントでわかるように、関連付けられたUserProfileオブジェクトを取得できますが、そこからUserProfileテーブルに追加のデータ(ロール)を格納する場所がわかりません。すべてのドキュメントは私に次のように伝えています:
get_profile() このユーザーのサイト固有のプロファイルを返します。現在のサイトでプロファイルが許可されていない場合はdjango.contrib.auth.models.SiteProfileNotAvailableを発生させ、ユーザーがプロファイルを持っていない場合はdjango.core.exceptions.ObjectDoesNotExistを発生させます。
ここで表示できます:https ://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_profile
ただし、ドキュメントにはget_profile()
、返されるオブジェクトの種類や、それを使用してUserProfileテーブルに情報を格納する方法は記載されていません。