On Mon, 2009-05-04 at 11:52 -0700, hotani wrote:
> Most of the errors I'm seeing these days in my application are of the
> "NoneType object has no attribute...." variety. While this may be
> helpful on occasion on the development server, I really don't want it
> creeping up on production.
> 
> "Well fix them!" you say. Actually there is nothing to fix. This is
> expected. There are times when I'm calling an attribute of an object
> and it's just not going to be there. I would like to have an empty
> string returned, or 'None'--anything other than a nasty 500 error for
> the user.
> 
> This is a law database. The primary model is "Case". Cases have
> attorneys, judges, and so on. Some of the old cases don't have judges
> (for example). If I call case.judge.last_name, I get a "NoneType
> object has no attribute 'last_name'" error, when all I want is an
> empty string or "None."
> 
> If I try to do "my_wrapper_function(case.judge.last_name)", I end up
> with the same error. Attempting to create something to fix this has
> turned complicated and I'm wondering if there is some obvious way
> around this issue that I'm overlooking.
> 
> Does django have a built-in way of handling these? I know this error
> is handled on the template side, but these issues are in views. If not
> django, is there something in python?

The try...except statement pair are what you're after. If you're
expecting an exception to be raised and know how you want to handle it,
then catch the exception and handle it in the right place.
Alternatively, have a look at the getattr() function in Python.
Something like getattr(case.judge, "last_name", "") will probably be
what you're after.

In any case, all solutions to this are in the Python language. It's
normal attribute access stuff: if you try to access something that isn't
there, you'll get an exception. So either except to handle the
exception, or check the thing is there first. (Why are templates
different, you ask? Because templates aren't Python).

Regards,
Malcolm



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to