2016-12-31 62 views
2

我想要一种方法来检查是否有人用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") 
+1

有这样做的许多方面。你可以提供更多的上下文来缩小答案的范围。你有一个认证系统,即你可以检查'request.user.is_authenticated()'吗? – YPCrumble

+0

也许提供你的视图代码,因为这是最有可能发生这种检查的地方。 – YPCrumble

+0

@YPCrumble我用一个例子更新了这个问题。是的,我使用Django的身份验证系统。 –

回答

3

一种选择是把一个模型的方法对你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.......... 
+0

我不认为这是一个非常好的或优雅的解决方案,尤其是因为提问的人在整个网站的每一页上都需要这样的解决方案。您提供的此解决方案必须在所有页面上实施。 –

+0

@MarcusLind在下面看到我的回复 - 如果用户没有提供所需的数据,则不会登录用户,因此这是唯一需要调用代码的地方。 – YPCrumble

0

的最好方式是创建一个自定义上下文处理器,用于检查当前用户的注册数据,并在context中设置一个布尔值,该值可在每个模板和视图中访问。它可以避免必须一遍又一遍地在所有视图上调用代码。

你可以阅读上下文处理器在这里: https://docs.djangoproject.com/en/1.10/ref/templates/api/

+0

我喜欢你的想法,但这只是意味着在每个模板中反复检查布尔值。认证系统意味着只有一个地方可以调用代码 - 当用户尝试登录时。如果他们没有通过测试,他们不会登录;他们必须提供更多的数据。我认为另一种实现你要找的东西的方法是定制中间件,但缺点是你必须指定任何不需要保护的页面。 – YPCrumble

相关问题