2016-10-09 9 views
0

私は基本的なDjangoサイトをセットアップし、サイトにログインを追加しました。さらに、私は、組み込みのユーザー1を拡張するStudent(Profile)モデルを作成しました。ユーザーモデルとOneToOneの関係にあります。ユーザプロファイルやその他のDjangoオブジェクトを自動的に作成する

しかし、まだ初めてログインしたときに自動的にプロファイルを作成するように強制されていません。これを作成せずに何かを進めることはできません。

私は、ビューで次のように定義することで試してみました:

def UserCheck(request): 
    current_user = request.user 
    # Check for or create a Student; set default account type here 
    try: 
     profile = Student.objects.get(user = request.user) 
     if profile == None: 
      return redirect('/student/profile/update') 
     return True 
    except: 
     return redirect('/student/profile/update') 

そして、その後には、以下を追加:

UserCheck(request) 

私の意見のそれぞれの上部にあります。しかしこれは、ユーザーをプロファイルを作成するようにリダイレクトするようなことはありません。

ユーザーが上記のプロファイルオブジェクトを強制的に作成するようにするための最良の方法はありますか?

答えて

2

Djangoのuser_passes_testデコレータ(documentation)と似たようなことをしようとしているようです。

# Side note: Classes are CamelCase, not functions 
def user_check(user): 
    # Simpler way of seeing if the profile exists 
    profile_exists = Student.objects.filter(user=user).exists() 
    if profile_exists: 
     # The user can continue 
     return True 
    else: 
     # If they don't, they need to be sent elsewhere 
     return False 

その後、あなたはあなたの意見にデコレータを追加することができます:あなたはこのに持っている機能をオンにすることができ

from django.contrib.auth.decorators import user_passes_test 

# Login URL is where they will be sent if user_check returns False 
@user_passes_test(user_check, login_url='/student/profile/update') 
def some_view(request): 
    # Do stuff here 
    pass 
関連する問題