Reputation: 295
I need to get the model name of an object in a javascript function inside the template file. I have tried two methods. 1) Writing a custom templatetag
@register.filter
def get_model_name(value):
name = str(value.__class__.__name__)
return name
Second is writing a method in the model itself
def getModelName(self):
return 'Model1'
JS
var objectType = {{object.getModelName}};
var objectType = {{object | get_model_name}};
I get the correct name as output but its not in string format. So I get an error saying that Model1 is undefined. Its being treated like a variable.
Any way to get this in string format. I need the name of the model in string format in my var objectType
Upvotes: 0
Views: 924
Reputation: 27112
It is a python string...you're just not passing it to JS as a string. You need to quote the value that is returned:
var objectType = '{{ object|get_model_name }}';
Upvotes: 3