Reputation: 5
I am developing a simple Django project. However, I am not very familiar with python as well as Django. It keeps throwing "NameError".
In my template, the code looks like this:
{% for habbit_source in habbit_source_list %}
<span class="habbit-hide">{{habbit_source.get_tomato_achieve}}</span>
...
{% endfor %}
get_tomato_achieve
is a function of the Model class: task.models.HabbitSource
, which is defined like this:
def get_tomato_achieve(self):
return rules.get_achieve_tomato(self)
In rules.py
, I want to judge the type of input parameter at the beginning of get_tomato_achieve(habbit)
, however whether I use
if type(habbit) == task.models.HabbitSource:
or
if isinstance(habbit, task.models.HabbitSource):
It will throw NameError: Name task is not defined.
(Of course it's defined. it's my app's name.)
And if I write from task.models import HabbitSource
, it will throw ImportError: cannot import HabbitSource
.
I really don't know how to solve this.
Thanks!
Upvotes: 0
Views: 596
Reputation: 599856
Just because task
is the name of your application, that's no reason to think it would be defined in any particular module. Python's name scoping rules are very very simple: nothing is defined unless it is imported or assigned in that module. If you don't have anything that defines the name task
, it remains undefined.
As for why you can't do from task.models import HabbitSource
, you might have a circular dependency. If rules
imports models
and models
imports rules
, the dependency cannot be resolved at import time, so you get that error.
One possibility would be to cheat and use the internal model name attribute, which is a string:
if habbit._meta.object_name == 'HabbitSource':
Alternatively, you could rethink your architecture: type checking is not usually idiomatic Python, normally you would simply define your class's methods appropriately and just call them.
Upvotes: 2