繁体   English   中英

确定新站点用户的最佳方法-Django

[英]Best way to determine a new site user - Django

我想要一种检查是否有人用django填写了个人资料信息(新用户)的方法。 如果他们没有,我想展示一个模态,直到所有信息都填写完毕,模态才会消失。 无论他们进入哪个页面,它都应显示此模式,直到填写完毕。

我是否应该使用javascript(ajax)进行路由检查,以进行检查并返回带有答案的json请求? 如果json对象说它们是新的,我将动态地将模式附加到屏幕上。

更新:我使用django的身份验证系统。 这是一个登录示例。检查将类似,但我将使用在另一个应用程序中创建的模型,该应用程序扩展了Django的基本用户类。 我称它为user_profile。 我可能会检查一下是否设置了用户的名字。 如果不是,我想执行检查。

    def auth_login(request):
    if request.POST:

        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user:
        # the password verified for the user
            if user.is_active:
                print("User is valid, active and authenticated")
                request.session['id'] = user.id
                request.session['email'] = user.email
                login(request, user)
                data = {}
                data['status'] = "login"
                return HttpResponse(json.dumps(data), content_type="application/json")
                #redirect
            else:
                print("The password is valid, but the account has been disabled!")
        else:
            # the authentication system was unable to verify the username and password
            print("The username and password were incorrect.")
            data = {}
            data['status'] = "The username and password are incorrect"
            return HttpResponse(json.dumps(data), content_type="application/json")

    return HttpResponse("hello")

一种选择是将模型方法放在user_profile的模型上:

class UserProfile(models.Model):
    name = CharField...
    ...other fields...

    def get_is_new(self):
        if self.name is None:  # You could include other checks as well
            return True
        return False

然后,您可以像这样检查视图:

def auth_login(request):
    if request.POST:

        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user:
        # the password verified for the user
            if user.is_active:
                print("User is valid, active and authenticated")
                if user.get_is_new() is True:
                    # Return the modal
                request.session['id'] = user.id
                .......rest of your code..........

最好的方法是创建一个自定义上下文处理器,该处理器将检查当前用户的注册数据并在可以在每个模板和视图中访问的context中设置一个布尔值。

这样可以避免在所有视图上一遍又一遍地调用代码。

您可以在此处阅读有关上下文处理器的信息: https : //docs.djangoproject.com/en/1.10/ref/templates/api/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM