1

What is the best practice for either testing or making sure that all your template variables are in fact existing.

Assume that we have the following template

<html>
  <div>{{ existing_object.non_existing_attribute }}</div>
</html>

We have an existing object. So we can't really test the response context like in the following answer: Django Unitest Checking Value Of Template Variable

There is string_if_invalid as described in the documentation. But that should only be used for debugging purposes.

Any insight on how to best avoid this would be helpful!

Edit: Let's assume that the non-existing attribute is a bug. Ie I misspelt the variable, because of this it's showing up as an empty string.

Edit2: This question has a lot better answers: https://stackoverflow.com/a/7854404/554903

Jonathan
  • 8,453
  • 9
  • 51
  • 74
  • Maybe you can create a template tag passing an object and then with python's hasatrr check if the object has the attribute you want to check – Dimitris Kougioumtzis Sep 28 '18 at 12:58
  • I think, the how depends on what you want to do if the attribute does not exist. E.g. do you want to show a default value or don't display the `div` at all? You can also just check `{% if existing_object.non_existing_attribute %}`, but that does not distinguish non-existing and non-truthy attributes. – user2390182 Sep 28 '18 at 12:59
  • @schwobaseggl Well, ideally I would like it to throw an error to be honest. I expected the attribute to exist on that object, but it doesn't. In python outside of templates this would get me an `AttributeError`. – Jonathan Sep 28 '18 at 13:03

2 Answers2

0

You can use the builtin template tag default_if_none.

{{ object.attribute|default_if_none:"Nothing" }}

  • 1
    I don't think this answers the question. The question deals - given I understand it correctly - with ensuring that all variables in the template are passed by the view. – Willem Van Onsem Sep 28 '18 at 13:00
0

I think the proper way to do this would be to have test specific settings and set a value for the setting string_if_invalid. So set the value to something like INVALID. And when you get the return of the response make sure that the template does not contain INVALID.

As the settings will only be available in your testing environment you'll never run the risk of getting the word INVALID into production.

Jonathan
  • 8,453
  • 9
  • 51
  • 74