【问题标题】:Create a User Profile or other Django Object automatically自动创建用户配置文件或其他 Django 对象
【发布时间】:2017-02-18 08:02:41
【问题描述】:

我已经设置了一个基本的 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 authentication django-models django-views profile


    【解决方案1】:

    看起来你正在尝试做一些类似于 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
    

    【讨论】:

      猜你喜欢
      • 2021-04-06
      • 2011-08-05
      • 2016-12-03
      • 2015-03-31
      • 2012-03-03
      • 1970-01-01
      • 2012-08-02
      • 2012-07-14
      • 2013-04-05
      相关资源
      最近更新 更多