0

I'm trying to work out an exception problem I've been having with django: I have a view with the following call with an url http://someurl.com/?items=1,2,3. I want to deal with cases where ?items= or ?items=somthing_bs. When I always get the error: local variable 'apps' referenced before assignment. Shouldn't it catch all the exceptions and errors that come it's way in the try clause? My code:

 def my_view(request):
    if request.GET.get('mashpoint'):
        try:
            item_ids = request.GET.get('mashpoint')
            item_ids = item_ids.split(',')
            apps = mpApp.objects.filter(mpitem__pk__in=item_ids).distinct()
            return render_to_response(template_name,context_instance=RequestContext(request,{'apps':apps,'item_ids':','.join(item_ids)}))
        except:
            return render_to_response(template_name,context_instance=RequestContext(request,{}))
    return render_to_response(template_name,context_instance=RequestContext(request,{}))   
1
  • Can you edit your post to fix the indentation? Commented Jan 17, 2012 at 16:07

3 Answers 3

2

The last render_to_response is outside the if block above it. So in cases where there's no items key in GET or the items key is empty (/path/?items=), apps is undefined.

It would be better to use:

if request.GET.has_key('items'):
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that's it.. I also revised the code the last bit had no point! Thanks!
0

The problem is probably in the second render_to_response statement. apps is being used when no value has been assigned to it.

Note: I'm assumming that that statement isn't included in the if statement above (as pointed out by Rob Wouters, indentation doesn't seem to be correct). Anyway, you can confirm by looking at the line number the error is being reported.

Comments

0

Move the second call to render_to_response inside the try block, it has no point where it is now, if the if block structure is like you posted. Otherwise you'll always get that error, since it's not a runtime error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.