def vote(request, post_id, vote_type): """ Creates a new PostVote object, and persists it to DB. Redirects user back to referer page. """ valid_vote_types = ('up', 'down') if vote_type not in valid_vote_types: messages.add_message(request, messages.INFO, 'Invalid vote type') return HttpResponseRedirect(request.META.get('HTTP_REFERER','/')) # make sure that this is a valid post_id try: post = Post.objects.get(pk=post_id) except Post.DoesNotExist: messages.add_message(request, messages.INFO, 'Invalid post_id') return HttpResponseRedirect(request.META.get('HTTP_REFERER','/')) score = 1 if (vote_type == 'up') else -1 # if this user has already attempted to cast a vote for this key/object_id # will throw integrity error, gloss over this for right now try: new_vote = PostVote(score=score, post=post, created_by=request.user) new_vote.save() except IntegrityError: pass messages.add_message(request, messages.INFO, 'Thank you for voting') return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
def create_post(request): """ Create a post (POST) or render a form (GET) to create a post, depending on the request type. """ if request.method == 'POST': form = FullPostForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.created_by = request.user new_post.save() # creating a PostVote of 0, # A PostVote is created here and initialized to 0 so that the ordering # works correctly... # This might be better off as a signal vote = PostVote(score=0, post=new_post) vote.save() return HttpResponseRedirect(new_post.get_absolute_url()) else: form = FullPostForm() return render(request, 'create_post.html', { 'form': form })
def test_vote_order_by_success(self): """ Tests that posts can be ordered by their votes. """ # create 2 posts post_one = Post(created_by=self.test_user, text='asdfasdf', title='post1') post_one.save() post_two = Post(created_by=self.test_user, text='asdfasdf', title='post2') post_two.save() post_three = Post(created_by=self.test_user, text='asdfasdf', title='post3') post_three.save() # give post_one a vote so it should show up first in ordering vote = PostVote(created_by=self.test_user, score=1, post=post_one) vote.save() vote = PostVote(created_by=self.test_user, score=0, post=post_two) vote.save() vote = PostVote(created_by=self.test_user, score=-1, post=post_three) vote.save() # get ordering order should be post_one, post_two, post_three # this should fail becuase an int comes Before None value in the order by function! posts = Post.objects.all() self.assertEqual([post.pk for post in posts], [1, 2, 3])