Skip to content

Add tag list view. Refactor getting tags with usage count. Implement … #238

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions bootcamp/articles/migrations/0002_auto_20200626_1410.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Generated by Django 3.0.7 on 2020-06-26 14:10

from django.db import migrations, models
import django.db.models.deletion
import taggit_selectize.managers


def recreate_tagged_items(apps, schema_editor):
TaggedArticle = apps.get_model('articles', 'TaggedArticle')
TaggedItem = apps.get_model('taggit', 'TaggedItem')

old_tagged_items = TaggedItem.objects.filter(content_type__model='article')
for old in old_tagged_items:
TaggedArticle.objects.create(tag=old.tag, content_object_id=old.object_id)
old_tagged_items.delete()


class Migration(migrations.Migration):

dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('articles', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='TaggedArticle',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content_object', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='articles.Article')),
('tag', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='articles_taggedarticle_items', to='taggit.Tag')),
],
options={
'abstract': False,
},
),
migrations.AlterField(
model_name='article',
name='tags',
field=taggit_selectize.managers.TaggableManager(help_text='A comma-separated list of tags.', through='articles.TaggedArticle', to='taggit.Tag', verbose_name='Tags'),
),
migrations.RunPython(recreate_tagged_items, reverse_code=migrations.RunPython.noop),
]
26 changes: 10 additions & 16 deletions bootcamp/articles/models.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
from django.conf import settings
from django.db import models
from django.db.models import Count
from django.db.models import Count, F
from django.utils.translation import ugettext_lazy as _

from slugify import slugify

from django_comments.signals import comment_was_posted
from markdownx.models import MarkdownxField
from markdownx.utils import markdownify
from taggit.managers import TaggableManager

from taggit_selectize.managers import TaggableManager
from taggit.models import TaggedItemBase

from bootcamp.notifications.models import Notification, notification_handler

Expand All @@ -25,20 +25,14 @@ def get_drafts(self):
"""Returns only the items marked as DRAFT in the current queryset."""
return self.filter(status="D")

def get_counted_tags(self):
tag_dict = {}
query = (
self.filter(status="P").annotate(tagged=Count("tags")).filter(tags__gt=0)
)
for obj in query:
for tag in obj.tags.names():
if tag not in tag_dict:
tag_dict[tag] = 1
@staticmethod
def get_counted_tags():
return TaggedArticle.objects.filter(content_object__status='P').order_by('tag__id').\
annotate(name=F('tag__name'), slug=F('tag__slug'),).values('slug', 'name').annotate(count=Count('tag'))

else: # pragma: no cover
tag_dict[tag] += 1

return tag_dict.items()
class TaggedArticle(TaggedItemBase):
content_object = models.ForeignKey('Article', on_delete=models.CASCADE)


class Article(models.Model):
Expand All @@ -61,7 +55,7 @@ class Article(models.Model):
status = models.CharField(max_length=1, choices=STATUS, default=DRAFT)
content = MarkdownxField()
edited = models.BooleanField(default=False)
tags = TaggableManager()
tags = TaggableManager(through=TaggedArticle)
objects = ArticleQuerySet.as_manager()

class Meta:
Expand Down
2 changes: 2 additions & 0 deletions bootcamp/articles/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from bootcamp.articles.views import (
ArticlesListView,
ArticlesByTagListView,
DraftsListView,
CreateArticleView,
EditArticleView,
Expand All @@ -11,6 +12,7 @@
app_name = "articles"
urlpatterns = [
url(r"^$", ArticlesListView.as_view(), name="list"),
url(r"^tag/(?P<slug>[-\w]+)/$", ArticlesByTagListView.as_view(), name="by_tag_list"),
url(r"^write-new-article/$", CreateArticleView.as_view(), name="write_new"),
url(r"^drafts/$", DraftsListView.as_view(), name="drafts"),
url(r"^edit/(?P<pk>\d+)/$", EditArticleView.as_view(), name="edit_article"),
Expand Down
18 changes: 17 additions & 1 deletion bootcamp/articles/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
from django.utils.translation import ugettext_lazy as _

from bootcamp.helpers import AuthorRequiredMixin
from bootcamp.articles.models import Article
from bootcamp.articles.models import Article, TaggedArticle
from bootcamp.articles.forms import ArticleForm

from taggit.views import TagListMixin


class ArticlesListView(LoginRequiredMixin, ListView):
"""Basic ListView implementation to call the published articles list."""
Expand All @@ -25,6 +27,20 @@ def get_queryset(self, **kwargs):
return Article.objects.get_published()


class ArticlesByTagListView(TagListMixin, ArticlesListView):
template_name = 'articles/article_list.html'

def get_queryset(self, **kwargs):
qs = Article.objects.filter(
pk__in=TaggedArticle.objects.filter(tag=self.tag).values_list("content_object_id", flat=True))
return qs.get_published()

def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context["filtered_by_tag"] = self.tag
return context


class DraftsListView(ArticlesListView):
"""Overriding the original implementation to call the drafts articles
list."""
Expand Down
2 changes: 2 additions & 0 deletions bootcamp/templates/articles/article_create.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
{% load crispy_forms_tags %}

{% block head %}
{# Load Jquery in head for keep taggit_serializer working #}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
{% endblock head %}

{% block content %}
Expand Down
11 changes: 7 additions & 4 deletions bootcamp/templates/articles/article_list.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="{% url 'news:list' %}">{% trans 'Home' %}</a></li>
<li class="breadcrumb-item active"><a href="{% url 'articles:list' %}">{% trans 'Articles' %}</a></li>
{% if filtered_by_tag %}
<li class="breadcrumb-item active">{{ filtered_by_tag }}</li>
{% endif %}
</ol>
</nav>
<div class="row">
Expand All @@ -38,8 +41,8 @@ <h2 class="card-title">{{ article.title|title }}</h2>
{% trans 'Posted' %} {{ article.timestamp|naturaltime }}
<i class="lead fa fa-user"></i>
<a href="{% url 'users:detail' article.user.username %}">{{ article.user.get_profile_name|title }}</a>
{% for tag in article.tags.names %}
<a href="#">{{ tag }}</a>
{% for tag in article.tags.all %}
<a href="{% url 'articles:by_tag_list' slug=tag.slug %}">{{ tag.name }}</a>
{% endfor %}
</div>
</div>
Expand Down Expand Up @@ -86,8 +89,8 @@ <h4 class="no-data">{% trans 'There is no published article yet' %}. <a href="{%
<div class="card my-4">
<h5 class="card-header">{% trans 'Cloud tag' %}</h5>
<div class="card-body">
{% for tag, count in popular_tags %}
<a href="#"><span class="badge badge-info">{{ count }} {{ tag }}</span></a>
{% for tag in popular_tags %}
<a href="{% url 'articles:by_tag_list' slug=tag.slug %}"><span class="badge badge-info">{{ tag.count }} {{ tag.name }}</span></a>
{% endfor %}
</div>
</div>
Expand Down
2 changes: 2 additions & 0 deletions bootcamp/templates/articles/article_update.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
{% load crispy_forms_tags %}

{% block head %}
{# Load Jquery in head for keep taggit_serializer working #}
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
{% endblock head %}

{% block content %}
Expand Down
5 changes: 5 additions & 0 deletions config/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"graphene_django",
"markdownx",
"taggit",
"taggit_selectize",
]
LOCAL_APPS = [
"bootcamp.users.apps.UsersConfig",
Expand Down Expand Up @@ -259,3 +260,7 @@

# GraphQL settings
GRAPHENE = {"SCHEMA": "config.schema.schema"}

# taggit-selectize settings
TAGGIT_TAGS_FROM_STRING = 'taggit_selectize.utils.parse_tags'
TAGGIT_STRING_FROM_TAGS = 'taggit_selectize.utils.join_tags'
2 changes: 2 additions & 0 deletions config/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
url(r"^messages/", include("bootcamp.messager.urls", namespace="messager")),
url(r"^qa/", include("bootcamp.qa.urls", namespace="qa")),
url(r"^search/", include("bootcamp.search.urls", namespace="search")),
url(r'^taggit/', include('taggit_selectize.urls')),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

if settings.DEBUG:
Expand Down
1 change: 1 addition & 0 deletions requirements/base.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ django-markdownx # https://github.com/neutronX/django-markdownx
django-redis # https://github.com/niwinz/django-redis
django-taggit # https://github.com/alex/django-taggit
sorl-thumbnail # https://github.com/jazzband/sorl-thumbnail
taggit-selectize # https://github.com/chhantyal/taggit-selectize

# Channels
# ------------------------------------------------------------------------------
Expand Down