Filtering and redirecting in django view does not perform as expected

I have a very simple view that checks if something exists and then redirects if it is not. For some reason this does not work. The exception remains shooting. I checked that there are records in the database that need to be returned.

Any suggestions are welcome.

@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')
+3
source share
1 answer

Are you trying to use an if statement and exist ()? I think it is easier.

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')

This may not be the most beautiful way, but I think it should work.

+2
source

All Articles