Skip to content

Instantly share code, notes, and snippets.


vitorfs/ Secret

Created October 8, 2017 14:28
Show Gist options
  • Save vitorfs/16f0ac257439245fa6645af259d8846f to your computer and use it in GitHub Desktop.
Save vitorfs/16f0ac257439245fa6645af259d8846f to your computer and use it in GitHub Desktop.
from django.db.models import Count
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import get_object_or_404, redirect, render
from django.views.generic import UpdateView, ListView
from django.utils import timezone
from django.utils.decorators import method_decorator
from .forms import NewTopicForm, PostForm
from .models import Board, Post, Topic
class BoardListView(ListView):
model = Board
context_object_name = 'boards'
template_name = 'home.html'
def board_topics(request, pk):
board = get_object_or_404(Board, pk=pk)
queryset = board.topics.order_by('-last_updated').annotate(replies=Count('posts') - 1)
page = request.GET.get('page', 1)
paginator = Paginator(queryset, 20)
topics =
except PageNotAnInteger:
# fallback to the first page
topics =
except EmptyPage:
# probably the user tried to add a page number
# in the url, so we fallback to the last page
topics =
return render(request, 'topics.html', {'board': board, 'topics': topics})
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 =
topic.board = board
topic.starter = request.user
return redirect('topic_posts', pk=pk,
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)
topic.views += 1
return render(request, 'topic_posts.html', {'topic': topic})
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 =
post.topic = topic
post.created_by = request.user
return redirect('topic_posts', pk=pk, topic_pk=topic_pk)
form = PostForm()
return render(request, 'reply_topic.html', {'topic': topic, 'form': form})
@method_decorator(login_required, name='dispatch')
class PostUpdateView(UpdateView):
model = Post
fields = ('message', )
template_name = 'edit_post.html'
pk_url_kwarg = 'post_pk'
context_object_name = 'post'
def get_queryset(self):
queryset = super().get_queryset()
return queryset.filter(created_by=self.request.user)
def form_valid(self, form):
post =
post.updated_by = self.request.user
post.updated_at =
return redirect('topic_posts',,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment