Skip to content
Advertisement

How to check if the object has property in view in Django?

I am trying to get the documents property in a general function, but a few models may not have the documents attribute. Is there any way to first check if a model has the documents property, and then conditionally run code?

JavaScript

Advertisement

Answer

You can use hasattr() to check to see if model has the documents property.

JavaScript

However, this answer points out that some people feel the “easier to ask for forgiveness than permission” approach is better practice.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement