We generally want to have as simple views as possible, because it doesn't make sense to put functionality there. Functionality should be put in model files or utility files.
So in this part of the series, we will add a custom function to one of our models. Open up "category/models.py":
class Category(models.Model):
title = models.CharField(max_length=255)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return self.title
def number_of_tasks(self):
return self.tasks.count()
As you can see here, we've added a new method to the Category model. This could now be used in templates and similar like this:
{{ category.number_of_tasks }}
Table of contents
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page
- 16. Separate url files and why
- 17. Adding tasks in the front end
- 18. Editing tasks
- 19. Completing and deleting tasks
- 21. Prettying up the design a little bit
- 22. Make it possible to sign up
- 23. Logging in
- 24. Logging out
- 25. Show only your data
- 26. Creating a model function