Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
自动创建用户配置文件或其他Django对象_Django_Authentication_Django Models_Django Views_Profile - Fatal编程技术网

自动创建用户配置文件或其他Django对象

自动创建用户配置文件或其他Django对象,django,authentication,django-models,django-views,profile,Django,Authentication,Django Models,Django Views,Profile,我已经建立了一个基本的Django网站,并添加了登录到该网站。此外,我还创建了一个学生(Profile)模型,该模型扩展了内置的用户模型。它与用户模型之间有一种“一对一”的关系 但是,我还没有正确地强制用户在第一次登录时自动创建配置文件。我怎样才能确保他们在没有创造的情况下无法完成任何事情 我尝试在视图中定义以下内容: def UserCheck(request): current_user = request.user # Check for or create a Stude

我已经建立了一个基本的Django网站,并添加了登录到该网站。此外,我还创建了一个学生(Profile)模型,该模型扩展了内置的用户模型。它与用户模型之间有一种“一对一”的关系

但是,我还没有正确地强制用户在第一次登录时自动创建配置文件。我怎样才能确保他们在没有创造的情况下无法完成任何事情

我尝试在视图中定义以下内容:

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)
在我的每个观点的顶部。然而,这似乎从未重定向用户以创建配置文件


有没有最好的方法来确保用户被强制在上面创建一个profile对象?

看起来您正在尝试做类似于Django的
User\u passes\u test
decorator()的事情。您可以将现有功能转换为:

# 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的
user\u passes\u test
decorator()的操作。您可以将现有功能转换为:

# 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