Skip to content

Instantly share code, notes, and snippets.

@vitorfs

vitorfs/views.py Secret

Created Oct 1, 2017
Embed
What would you like to do?
from django.db.models import Count
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from .forms import NewTopicForm, PostForm
from .models import Board, Post, Topic
def home(request):
boards = Board.objects.all()
return render(request, 'home.html', {'boards': boards})
def board_topics(request, pk):
board = get_object_or_404(Board, pk=pk)
topics = board.topics.order_by('-last_updated').annotate(replies=Count('posts') - 1)
return render(request, 'topics.html', {'board': board, 'topics': topics})
@login_required
def new_topic(request, pk):
board = get_object_or_404(Board, pk=pk)
if request.method == 'POST':
form = NewTopicForm(request.POST)
if form.is_valid():
topic = form.save(commit=False)
topic.board = board
topic.starter = request.user
topic.save()
Post.objects.create(
message=form.cleaned_data.get('message'),
topic=topic,
created_by=request.user
)
return redirect('topic_posts', pk=pk, topic_pk=topic.pk)
else:
form = NewTopicForm()
return render(request, 'new_topic.html', {'board': board, 'form': form})
def topic_posts(request, pk, topic_pk):
topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk)
return render(request, 'topic_posts.html', {'topic': topic})
@login_required
def reply_topic(request, pk, topic_pk):
topic = get_object_or_404(Topic, board__pk=pk, pk=topic_pk)
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.topic = topic
post.created_by = request.user
post.save()
return redirect('topic_posts', pk=pk, topic_pk=topic_pk)
else:
form = PostForm()
return render(request, 'reply_topic.html', {'topic': topic, 'form': form})
@id-den
Copy link

id-den commented Apr 22, 2018

Hi, @vitorfs
Calculation works wrong.
I think, need to use without -1
topics = board.topics.order_by('-last_updated').annotate(replies=Count('posts') - 1 )

@northout-soujany
Copy link

northout-soujany commented Feb 11, 2019

Same here,
Calculation works wrong.
Removing -1 worked for me.

@darren573
Copy link

darren573 commented Mar 24, 2019

I removed -1 ,
but it still works wrong without any data in replies line.
anyone have ideas?

@wolfXSir
Copy link

wolfXSir commented May 10, 2022

I removed -1 , but it still works wrong without any data in replies line. anyone have ideas?

{% for topic in topics %}
you should check topics.html above line.

boards/views.py
def board_topics(request, pk):
board = get_object_or_404(Board, pk=pk)
topics = board.topics.order_by('last_updated').annotate( replies=Count('posts') -1 )
return render(request, 'topics.html', {'board': board, 'topics': topics})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment