I have a model which store generic foreign keys to different objects. I am displaying the list somewhere and due to space constraint I want to splice the object name.
So I am doing the following
{{list_object.content_object|slice:":20"}}
but this does not work. However when I do
{{list_object.content_object.title|slice:":20"}}
the slicing works. However I cannot use this, as content_object is a generic foreign key and every object ma not have an attribute named title.
Please help!
When you do slice directly on the object, Django never calls
__unicode__, but rather passes the object directly into the filter. This is the actual behavior that should happen. When you do{{ some_object }}in your template, Django only auto-magically calls__unicode__for you because it needs to print out something.Your best bet would be to add a method to your model to provide a shortened name, and then use that method in your template:
And in your template:
Or technically you could merely proxy the
__unicode__call and handle it in the template however you want:And in your template:
Whichever works best in your scenario.
Actually one more alternative would be to create a simple template filter to return the unicode value of an object:
Then, in your template:
Don’t you love options? 😉