【问题标题】:django view function code runs after returndjango查看函数代码返回后运行
【发布时间】:2010-12-01 04:57:57
【问题描述】:

我有一个看起来像...的 django 视图

def add_user(请求): 如果 User.objects.get(username__exact = request.POST['username']): context = { 'message': "用户名已被占用"} return render_to_response("mytemplate.html", context, RequestContext(request)) newUser = User(username="freeandclearusername") 新用户.save() #then 其他与设置新用户相关的代码。

即使初始条件语句失败并且调用了“return render_to_response()”,与设置用户相关的其他代码仍然运行。

页面使用正确的上下文呈现,但其他信息在初始返回后添加到数据库中。我以为“return render_to_response()”后面的代码不会运行。

谁能证实或解释这一点?

更新....

好吧,如果我添加一个条件......

def add_user(request):
    if User.objects.get(username__exact = request.POST['username']):
        bad_user = True
        context = { 'message': "Username already taken"}
        return render_to_response("mytemplate.html", context, RequestContext(request))

    newUser = User(username="freeandclearusername")
    newUser.save()

    if bad_user != True:
        #then other code that is related to setting up a new user.
        context = { 'message': "Username is great!!!!!"}
        return render_to_response("mytemplate.html", context, RequestContext(request))

这符合预期。此外,如果我删除 RequestConext() 它似乎也表现正确。

有什么想法吗?我认为问题在于我如何使用 RequestContext。

【问题讨论】:

  • render_to_response 通常将 RequestContext 作为关键字参数,称为“context_instance”,即 render_to_response("mytemplate.html", context, context_instance=RequestContext(request)) 但我不会立即看到影响你的代码执行...

标签: python django views


【解决方案1】:

return 语句确实会终止函数。所以如果你看到其他代码正在执行,你要么

  • 不要执行 return 语句,从而以某种方式产生不同的输出,或者
  • 有其他代码(在调用函数之前,或在中间件中)使数据库发生变化。

【讨论】:

    【解决方案2】:

    你是对的,假设你的条件得到满足,视图将在你的 return 语句中退出。我能想到的唯一还没有提到的另一件事是缩进——仔细检查你没有混合使用制表符和空格。这有时会导致意想不到的结果。

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多