ip.
ip.

Reputation: 3314

Django/Python Exceptions not working?

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,{}))   

Upvotes: 0

Views: 155

Answers (3)

Chris Pratt
Chris Pratt

Reputation: 239290

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

Upvotes: 2

Samuele Mattiuzzo
Samuele Mattiuzzo

Reputation: 11038

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.

Upvotes: 0

jcollado
jcollado

Reputation: 40374

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.

Upvotes: 0

Related Questions