What if a user wants to bookmark a masterpiece of an article and come back to it every once in a while? We'll enable our users to favourite specific articles.
The second to last feature we need is allowing users to favourite some articles, so that they are added to the user's profile for everyone to see.
In users/models.py:
1 2 3 4 5 6 7 8 91011121314151617
classProfile(models.Model):# ...favorites=models.ManyToManyField("articles.Article",related_name="favorited",blank=True)# ...deffavorite(self,article):"""Add article to Favorites"""self.favorites.add(article)defunfavorite(self,article):"""Remove article from Favorites"""self.favorites.remove(article)defhas_favorited(self,article):"""Return True if article is in Favorites, False otherwise"""returnself.favorites.filter(pk=article.pk).exists()
Checking if an article is in a user's favorites should be done in the view (or, even better, the model) instead of the template, but we would have to change our templates' structure and write new views if we wanted to include a Favorite button in the article_preview.html template.
<divclass="info"><ahref="{% url 'profile_detail' username=article.author.user.username %}"class="author">
{{ article.author.user.username }}
</a><spanclass="date">
{{ article.created_at|date:"D M d Y" }}
</span></div><divclass="pull-xs-right"><!-- new --> {% include 'article_favorite.html' %} <!-- new --></div><!-- new -->
<divclass="container"><divclass="row"><divclass="col-xs-12 col-md-10 offset-md-1"><divclass="articles-toggle"><ulclass="nav nav-pills outline-active"><liclass="nav-item"> {% url 'profile_detail' username=profile.user.username as profile_detail %} <!-- new from here --><ahref="{{ profile_detail }}"rel="prefetch"class="nav-link {% if request.path == profile_detail %}active{% endif %}"> My Articles
</a><!-- new to here --></li><liclass="nav-item"><!-- new from here --> {% url 'profile_favorites' username=profile.user.username as profile_favorites %}
<ahref="{{ profile_favorites }}"rel="prefetch"class="nav-link {% if request.path == profile_favorites %}active{% endif %}"> Favorited Articles
</a></li><!-- new to here --></ul></div> {% if request.path == profile_detail %} <!-- new --> {% include 'article_list.html' with articles=my_articles %}
{% elif request.path == profile_favorites %} <!-- new --> {% include 'article_list.html' with articles=favorited_articles %} <!-- new --> {% endif %} <!-- new --></div></div></div>