Skip to content
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

6.recomendar posts #6

Open
wants to merge 7 commits into
base: main
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
24 changes: 24 additions & 0 deletions mysite/blog/migrations/0003_auto_20211113_1857.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 3.2.9 on 2021-11-13 18:57

from django.db import migrations
import taggit.managers


class Migration(migrations.Migration):

dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('blog', '0002_comment'),
]

operations = [
migrations.AlterModelOptions(
name='comment',
options={'ordering': ('-created',)},
),
migrations.AddField(
model_name='post',
name='tags',
field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
),
]
2 changes: 2 additions & 0 deletions mysite/blog/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from django.db import models
from django.urls import reverse
from django.utils import timezone
from taggit.managers import TaggableManager


class PublishedManager(models.Manager):
Expand All @@ -24,6 +25,7 @@ class Post(models.Model):
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
objects = models.Manager()
published = PublishedManager()
tags = TaggableManager()

def get_absolute_url(self):
return reverse('blog:post_detail',
Expand Down
15 changes: 15 additions & 0 deletions mysite/blog/templates/blog/post/detail.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,22 @@ <h1> {{ post.title }}</h1>
<a href="{% url 'blog:post_share' post.id %}">
Share this post
</a>
<p class="tags">
Tags:
{% for tag in post.tags.all %}
<a href="{% url 'blog:post_list_by_tag' tag.slug %}">{{ tag.name }}</a>
{% if not.foorloop.last %}, {% endif %}
{% endfor %}
</p>
</p>
<h2>Similar Posts</h2>
{% for post in similar_posts %}
<p>
<a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
</p>
{% empty %}
There is no similar posts yet.
{% endfor %}
{% with comments.count as total_comments %}
<h2>
{{ total_comments }} comment{{total_comments|pluralize }}
Expand Down
13 changes: 12 additions & 1 deletion mysite/blog/templates/blog/post/list.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,27 @@

{% block content %}
<h1>My Blog</h1>
{% if tag %}
<h2>Posts tagged with "{{ tag.name }}"</h2>
{% endif %}
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="tags">
Tags:
{% for tag in post.tags.all %}
<a href="{% url 'blog:post_list_by_tag' tag.slug %}">{{ tag.name }}</a>
{% if not.foorloop.last %}, {% endif %}
{% endfor %}
</p>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|truncatewords:30|linebreaks }}
<hr>
{% endfor %}
{% include "../pagination.html" with page=page_obj %}
{% include "../pagination.html" with page=posts %}
{% endblock %}
10 changes: 8 additions & 2 deletions mysite/blog/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,14 @@
app_name = 'blog'

urlpatterns = [
# path('', views.post_list, name='post_list'),
path('', views.PostListView.as_view(), name='post_list'),
# Listar todos os posts
path('', views.post_list, name='post_list'),
# Listar posts baseado num tag
path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'),
# path('', views.PostListView.as_view(), name='post_list'),
# Detalhe de uma view
path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'),
# Compartilhar view
path('<int:post_id>/share/', views.post_share, name='post_share')

]
28 changes: 24 additions & 4 deletions mysite/blog/views.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from django.core.mail import send_mail
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponseRedirect
from django.db.models import Count
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView
from taggit.models import Tag

from mysite.blog.forms import EmailPostForm, CommentForm
from mysite.blog.models import Post
Expand All @@ -15,8 +16,16 @@ class PostListView(ListView):
template_name = 'blog/post/list.html' # O padrão é blog/list.html


def post_list(request):
def post_list(request, tag_slug=None):
object_list = Post.published.all()
tag = None
if tag_slug:
# A seguinte linha retorna o modelo obtido no banco a partir do tag_slug
tag = get_object_or_404(Tag, slug=tag_slug)
# De todos os posts publicados, filtra segundo a tag (objeto obtido anteriormente)
# Filtragem de um modelo baseado em outro
object_list = object_list.filter(tags__in=[tag])

paginator = Paginator(object_list, 3) # tres postagens em cada página
page = request.GET.get('page')
try:
Expand All @@ -27,7 +36,7 @@ def post_list(request):
except EmptyPage:
# Se a página estiver fora fo intervalo, exibe a última página de resultados
posts = paginator.page(paginator.num_pages)
return render(request, 'blog/post/list.html', {'posts': posts})
return render(request, 'blog/post/list.html', {'posts': posts, 'page': page, 'tag': tag})


def post_detail(request, year, month, day, post):
Expand All @@ -49,9 +58,20 @@ def post_detail(request, year, month, day, post):
else:
comment_form = CommentForm()

# Pag. 87
# Lista de id de tags do post atual. Ex.: <QuerySet [3, 5]>
post_tags_ids = post.tags.values_list('id', flat=True)

# Lista de postagens semelhantes Ex. :<QuerySet [<Post: __str__ do model>, <Post: __str__ do model >]>
similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)

# Lista dos 4 primeiros objetos tipo posts baseado no atributo criado -same_tags-
similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]

return render(request, 'blog/post/detail.html',
{'post': post, 'comments': comments,
'new_comment': new_comment, 'comment_form': comment_form})
'new_comment': new_comment, 'comment_form': comment_form,
'similar_posts': similar_posts})


def post_share(request, post_id):
Expand Down
3 changes: 2 additions & 1 deletion mysite/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mysite.blog.apps.BlogConfig'
'mysite.blog.apps.BlogConfig',
'taggit'
]

MIDDLEWARE = [
Expand Down
6 changes: 6 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
asgiref==3.4.1
Django==3.2.9
django-taggit==1.5.1
python-decouple==3.5
pytz==2021.3
sqlparse==0.4.2