And also: 1) You have misspelled description in the shorten_words method. In you model field definition, and in your length check it's "description" but in the print/return statements it's spelled "desciption".
2) The python slicing operator is clever enough to handle indexes that are out of bounds without errors, so self.description[0:20] would do nothing if len(self.description)<=20. Your method could simply be written as def shorten_words(self): return self.description[0:20] 3) You seem to be truncating by character count instead of word count, have you tried using the built in template tag truncatechars? https://docs.djangoproject.com/en/dev/ref/templates/builtins/#truncatechars Den lördagen den 12:e april 2014 kl. 16:29:26 UTC+2 skrev Sanjay Bhangar: > > On Sat, Apr 12, 2014 at 7:50 PM, Camilo Torres > <camilo...@gmail.com<javascript:>> > wrote: > > On Saturday, April 12, 2014 1:10:34 AM UTC-4:30, Kimitaka wrote: > >> > >> I wrote the function in my Product class in my models.py: > >> class Product(models.Model): > >> title = models.CharField(max_length=220) > >> description = models.CharField(max_length=3000, null=True, blank=True) > >> price = models.DecimalField(max_digits=1000, decimal_places=2, > null=True, > >> blank=True) > >> slug = models.SlugField() > >> timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) > >> updated = models.DateTimeField(auto_now_add=True, auto_now=False) > >> active = models.BooleanField(default=True) > >> > >> def __unicode__(self): > >> return self.title > >> class Meta: > >> ordering = ['title',] > >> > >> def shorten_words(self): > >> if len(self.description) > 20: > >> print self.desciption[0:20] > >> else: > >> print self.desciption > >> > >> > >> and I added a code in my products.html page: > >> {{ product.description.shorten_words() }} > > > > Hello, > > > > Should it be?: > > {{ product.shorten_words }} > > > > This. And in the desciption() method, you want to do "return > self.description[0:20] and not print..." - print will just print the > output in the console at that point - you need to "return" the value > from the method. > > So: > > def shorten_words(self): > if len(self.description) > 20: > return self.desciption[0:20] > else: > return self.desciption > > That, and {{ product.shorten_words }} in your template should do the > trick. > > All the best, > Sanjay > -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9178d216-4f3f-477b-a2ce-106e60c7eee8%40googlegroups.com. For more options, visit https://groups.google.com/d/optout.