自动创建用户配置文件或其他 Django 对象
Create a User Profile or other Django Object automatically
我已经设置了一个基本的 Django 站点并添加了该站点的登录名。此外,我还创建了一个学生(个人资料)模型,它扩展了内置的用户模型。它与用户模型具有 OneToOne 关系。
但是,我还没有正确地强制用户在他们第一次登录时自动创建配置文件。我如何确保他们在不创建配置文件的情况下无法完成任何事情?
我尝试在视图中定义以下内容:
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)
在我每个观点的顶部。然而,这似乎永远不会重定向用户以创建配置文件。
有没有最好的方法来确保用户被迫在上面创建配置文件对象?
看起来您正在尝试做类似于 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
我已经设置了一个基本的 Django 站点并添加了该站点的登录名。此外,我还创建了一个学生(个人资料)模型,它扩展了内置的用户模型。它与用户模型具有 OneToOne 关系。
但是,我还没有正确地强制用户在他们第一次登录时自动创建配置文件。我如何确保他们在不创建配置文件的情况下无法完成任何事情?
我尝试在视图中定义以下内容:
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)
在我每个观点的顶部。然而,这似乎永远不会重定向用户以创建配置文件。
有没有最好的方法来确保用户被迫在上面创建配置文件对象?
看起来您正在尝试做类似于 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