【问题标题】:Filtering and redirecting in a django view not performing as expected在 django 视图中过滤和重定向未按预期执行
【发布时间】:2014-02-01 20:59:37
【问题描述】:

我有一个非常简单的视图,它检查是否存在某些东西,如果不存在则重定向。由于某种原因,它不起作用。异常不断触发。我已验证数据库中有应返回的记录。

欢迎提出任何建议。

@login_required
def goal_display(request):
    user = get_object_or_404(User, id=request.user.id)

    if request.user != user:
        return permission_denied(request)

    try:
        goal = Goal.objects.filter(user=user).latest('created')

        return render_to_response('achieve/dashboard.html', {
                "goal": goal
                }, context_instance=RequestContext(request))
    except:
        return redirect('goal_add')

【问题讨论】:

  • Goal 有 created 和 user 字段吗?
  • 什么异常?裸except 很少是一个好主意,尝试将其更改为except Goal.DoesNotExist 并查看是否出现另一个错误(如果是这种情况,请发布完整的回溯)
  • 这太奇怪了。当我添加你的建议时,一切都开始工作了。这真的很奇怪。
  • 搞笑 :) 换回来是不是又坏了?
  • 'ghost' 错误可能与您的浏览器缓存重定向有关;您可能希望限制/禁用此类视图的缓存(例如使用装饰器 django.views.decorators.cache.never_cache)

标签: django django-views django-urls


【解决方案1】:

您是否尝试使用 if 语句和 exists()?我认为更容易。

def goal_display(request):
user = get_object_or_404(User, id=request.user.id)

if request.user != user:
    return permission_denied(request)

if(Goal.objects.filter(user=user).lastest('created').exists()):
    goal = Goal.objects.filter(user=user).latest('created')

    return render_to_response('achieve/dashboard.html', {
            "goal": goal
            }, context_instance=RequestContext(request))
else:
    return redirect('goal_add')

也许不是最漂亮的方式,但我认为它应该有效。

【讨论】:

    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    相关资源
    最近更新 更多