I have the following model:
class News(models.Model):
news_text = models.TextField(null=True)
... # other fields
with the following view:
def news(r):
news= News.objects
values = {'news':news}
return render(r,'webapp1/news.html',values)
I want to show in the template a substring for the column news_text, till the first 'dot' occurrence, like:
{{news.news_text| split('.')[0] }}
Tried this in template but got: "invalid filter: 'split'".
First post on stackoverflow ;)
CodePudding user response:
Django has a limited set of builtin template filters and there is no split
filter.
Also in Django templates you can access object's attributes or methods like {{my_dict.keys}}
, but you can't pass any arguments. So you can't do things like {{news.news_text.split('.')}}
as well.
All of this is done with intention to force you to separate logic from templates. So for your example probably will be better to define a special context variable and pass it into template's rendering context, like:
def news(r):
news = News.objects.all().get() # don't forget to call some filters on object manager
context = {
'news': news,
'headlines': news.news_text.split('.')[0],
}
return render(r, 'webapp1/news.html', context)
Also note that plural model names may be confusing: is it an array of news in each entry, or not?
Nevertheless you can create custom template tags and filters (and in many cases you should) to solve your problem.