Django Views - 它是如何工作的?

时间:2014-09-02 21:08:34

标签: python django

我对Django的观点如何运作有点困惑。我认为它有效:

  1. 用户按下了html页面上的按钮
  2. 该操作链接到一个视图,因此它转到url.py中定义的函数,然后它执行一些逻辑。
  3. 但是下面我有一个index.html页面,如果用户没有登录,它会将用户重定向到登录页面:

    def index(request):
        if not request.user.is_authenticated():
            return redirect('/login.html')
        else:
            result = Hello_World.delay()
            somethingDownByCelery = result.get(timeout=2)
            context = {'somethingDownByCelery': somethingDownByCelery, 'userName': request.user.username}
            return render(request, 'webapp/index.html', context)
    

    然后我有一个login.html,我有一个记录器,记录每个网页上的用户行为。

    def loginUser(request):
        logger = logging.getLogger('views.logger.login')
        try:
            username = request.POST['username'];
            logger.info("User:" + username + " in Login Page");
        except:
            logger.error("Cannot Identify User");
    
        type = ""
    
        try:
            type = request.POST['submit']
            logger.info("User:" + username + " requests:" + type);
        except MultiValueDictKeyError:
            logger.error("Cannot Identify User's Request");
    
        try:
            username = request.POST['username']
            password = request.POST['password']
    
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return redirect('index.html')
                else:
                    return redirect('disabled.html')
            else:
                condition = "Invalid Login"
                context = {'condition': condition}
                return render(request, 'webapp/login.html', context)
        except MultiValueDictKeyError:
            context = None
            return render(request, 'webapp/login.html', context)
    

    问题是,当网页刷新或重定向到时,当我尝试使用用户名和提交请求POST时,在两个例外中会得到两个logger.error,因为我认为行为是1(按网页中的按钮)然后2(在视图中运行该功能)。

    然而,不知何故,它首先通过整个函数然后生成一个网页,这是一个3步骤?

1 个答案:

答案 0 :(得分:3)

当Django执行重定向时,它会在呈现实际页面之前首先执行该视图的代码。您的代码正在执行loginUser(),并在第一个和第二个try块中触发异常,这会导致您的记录器语句。

因此,假设您来自索引并且未经过身份验证,则过程如下:

  • 指数()
    • 重定向(' /login.html')[这将调用映射到该网址的任何视图;你可能想考虑使用url resolution django offers]
  • loginUser()
    • 返回渲染(请求,' webapp / login.html',上下文)
  • 创建html并将其返回给用户
相关问题