def test_edit_invalid(self): request = self.request_factory.post('/', {}) form = AnswerForm(request.POST, instance=self.answer) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['answer'], ['This field is required.']) self.assertEqual(Action.objects.count(), 0, 'Invalid form submission should not result in an action' )
def answer_create_edit(request, question_slug, answer_pk=None): question = get_object_or_404(Question, slug=question_slug) if answer_pk: answer = get_object_or_404(Answer, pk=answer_pk) else: answer = Answer(user=request.user, question=question) answer_form = AnswerForm(request.POST or None, instance=answer) if answer_form.is_valid(): answer_form.save() return redirect(answer) return redirect(question)
def test_edit_valid(self): post_data = { 'answer': self.get_random_string(), } request = self.request_factory.post('/', post_data) form = AnswerForm(request.POST, instance=self.answer) if form.is_valid(): form.save() self.assertEqual(Action.objects.count(), 0, 'editting an answer should not result in an action' ) else: self.fail('Form should be valid')
def test_create_valid(self): post_data = { 'answer': self.get_random_string(), } request = self.request_factory.post('/', post_data) answer = Answer(user=self.create_user(), question=self.question) form = AnswerForm(request.POST, instance=answer) if form.is_valid(): form.save() self.assertEqual(Action.objects.count(), 1, 'Creating an answer should result in an action' ) else: self.fail('Form should be valid')
def question_detail(request, question_slug): question = get_object_or_404(Question, slug=question_slug) answers = question.answers.all() context = { 'question': question, 'answers': answers, } if request.user.is_authenticated(): votes = request.user.answer_votes.filter(question=question) \ .values_list('pk', flat=True) context.update({ 'votes': votes, 'answer_create_form': AnswerForm(), }) return render(request, 'qanda/question_detail.html', context)