Repository: kartoza/prj.app

Issue:
Special view for answers
Given a section, we should have a view showing all answers (for no staff user)


Discussion:
Can you elaborate this @Gustry ?
I think he means like a single page view that says

Module 1 Question 1  Correct Answers: a,b
Module 1 Question 2  Correct Answers: c,b
Module 2 Question 1  Correct Answers: d,b

Resolving patch:
diff --git a/django_project/lesson/urls.py b/django_project/lesson/urls.py
--- a/django_project/lesson/urls.py
+++ b/django_project/lesson/urls.py
@@ -38,6 +38,7 @@
     WorksheetPrintView,
     WorksheetOrderView,
     WorksheetOrderSubmitView,
+    WorksheetModuleQuestionAnswers,
 )
 from lesson.views.specification import (
     SpecificationCreateView,
@@ -85,6 +86,12 @@
               '(?P<section_slug>[\w-]+)/detail/(?P<pk>[\w-]+)/$',
         view=WorksheetDetailView.as_view(),
         name='worksheet-detail'),
+
+    url(regex='^(?P<project_slug>[\w-]+)/section/'
+              '(?P<section_slug>[\w-]+)/answers/(?P<pk>[\w-]+)/$',
+        view=WorksheetModuleQuestionAnswers.as_view(),
+        name='worksheet-module-answers'),
+
     url(regex='^(?P<project_slug>[\w-]+)/section/'
               '(?P<section_slug>[\w-]+)/print/(?P<pk>[\w-]+)/$',
         view=WorksheetPrintView.as_view(),
diff --git a/django_project/lesson/views/worksheet.py b/django_project/lesson/views/worksheet.py
--- a/django_project/lesson/views/worksheet.py
+++ b/django_project/lesson/views/worksheet.py
@@ -20,12 +20,14 @@
 from lesson.forms.worksheet import WorksheetForm
 from lesson.models.answer import Answer
 from lesson.models.further_reading import FurtherReading
-from lesson.models.section import Section
 from lesson.models.specification import Specification
 from lesson.models.worksheet import Worksheet
 from lesson.models.worksheet_question import WorksheetQuestion
 from lesson.utilities import re_order_features
 
+from base.models.project import Project
+from ..models.section import Section
+
 
 class WorksheetMixin(object):
     """Mixin class to provide standard settings for Worksheet."""
@@ -257,3 +259,50 @@ def post(self, request, *args, **kwargs):
         section = Section.objects.get(slug=kwargs.get('section_slug'))
         worksheets = Worksheet.objects.filter(section=section)
         return re_order_features(request, worksheets)
+
+
+
+class WorksheetModuleQuestionAnswers(LoginRequiredMixin, WorksheetMixin,
+                                     DetailView):
+    """Show correct answers to module questions.
+
+    :param request: HttpRequest object
+    :type request: HttpRequest
+    """
+    context_object_name = 'worksheets'
+    template_name = 'worksheet/question_answers.html'
+
+    def get_context_data(self, **kwargs):
+        """Create context for use in the templates."""
+
+        context = super(WorksheetModuleQuestionAnswers,
+                        self).get_context_data(**kwargs)
+        project_slug = self.kwargs.get('project_slug', None)
+        section_slug = self.kwargs.get('section_slug', None)
+        project = get_object_or_404(Project, slug=project_slug)
+
+        context['sections'] = Section.objects.filter(project=project,
+                                                     slug=section_slug)
+        for section in context['sections']:
+            query_set = Worksheet.objects.filter(section=section)
+            context['worksheets'] = []
+
+            for worksheet in query_set:
+                worksheet_json = {'worksheet': worksheet,
+                                  'question_answers': []
+                                  }
+
+                worksheet_questions = WorksheetQuestion.objects.filter(
+                        worksheet=worksheet.pk)
+
+                for question in worksheet_questions:
+                    question_json = {'question': question,
+                                     'answer': []
+                                     }
+                    answers = Answer.objects.filter(question=question)
+
+                    for answer in answers:
+                        question_json['answer'].append(answer)
+                    worksheet_json['question_answers'].append(question_json)
+                context['worksheets'].append(worksheet_json)
+        return context


Test patch:
diff --git a/django_project/lesson/tests/test_worksheet_views.py b/django_project/lesson/tests/test_worksheet_views.py
new file mode 100644
--- /dev/null
+++ b/django_project/lesson/tests/test_worksheet_views.py
@@ -0,0 +1,144 @@
+# coding: utf-8
+"""Unit tests for worksheet views."""
+
+__author__ = 'Alison Mukoma <alison@kartoza.com>'
+__copyright__ = 'kartoza.com'
+
+
+import logging
+
+from django.test import TestCase, override_settings, Client
+from django.core.urlresolvers import reverse
+
+from lesson.tests.model_factories import WorksheetF
+from lesson.tests.model_factories import SectionF
+from base.tests.model_factories import ProjectF
+from core.model_factories import UserF
+
+
+class TestViews(TestCase):
+    """Tests that Lesson Section views work."""
+
+    @override_settings(VALID_DOMAIN = ['testserver', ])
+    def setUp(self):
+        """
+        Setup before each test
+        We force the locale to en otherwise it will use
+        the locale of the host running the tests and we
+        will get unpredictable results / 404s
+        """
+
+        self.client = Client()
+        self.client.post(
+                '/set_language/', data = {'language': 'en'})
+        logging.disable(logging.CRITICAL)
+        self.user = UserF.create(
+            **{'username': 'sonlinux', 'is_staff': True})
+        # Something changed in the way factoryboy works with django 1.8
+        # I think - we need to explicitly set the users password
+        # because the core.model_factories.UserF._prepare method
+        # which sets the password is never called. Next two lines are
+        # a work around for that - sett #581
+        self.user.set_password('password')
+        self.user.save()
+
+        # Create project
+        self.test_project = ProjectF.create()
+
+        # Create section
+        self.test_section = SectionF.create(project=self.test_project)
+        self.test_worksheet = WorksheetF.create(section=self.test_section)
+        self.kwargs_project = {'project_slug': self.test_section.project.slug}
+        self.kwargs_section = {'slug': self.test_section.slug}
+        self.kwargs_section_full = {
+            'project_slug': self.test_section.project.slug,
+            'slug': self.test_section.slug
+        }
+        self.kwargs_worksheet_full = {
+            'project_slug': self.test_section.project.slug,
+            'section_slug': self.test_section.slug,
+            'pk': self.test_worksheet.pk
+        }
+
+    @override_settings(VALID_DOMAIN = ['testserver', ])
+    def test_WorksheetCreateView(self):
+        """Test accessing worksheet create view with no login."""
+
+        post_data = {
+            'module': u'Demo worksheet name',
+            'title': u'Demo worksheet title',
+            'section': self.test_section.id,
+        }
+        response = self.client.post(
+                reverse('worksheet-create', kwargs = {
+                    'project_slug': self.test_section.project.slug,
+                    'section_slug': self.test_section.slug}),
+                post_data)
+        self.assertEqual(response.status_code, 302)
+
+    @override_settings(VALID_DOMAIN = ['testserver', ])
+    def test_WorksheetCreateView_with_login(self):
+        """Test accessing worksheet create view with login."""
+
+        status = self.client.login(username='sonlinux', password='password')
+        self.assertTrue(status)
+        post_data = {
+            'module': u'Demo worksheet name',
+            'title': u'Demo worksheet title',
+            'section': self.test_section.id,
+        }
+        response = self.client.post(
+                reverse('worksheet-create', kwargs = {
+                    'project_slug': self.test_section.project.slug,
+                    'section_slug': self.test_section.slug}),
+                post_data)
+
+        self.assertEqual(response.status_code, 200)
+
+    @override_settings(VALID_DOMAIN = ['testserver', ])
+    def test_WorksheetDetailView(self):
+        """Tests accessing worksheet detail view."""
+
+        response = self.client.get(reverse(
+                'worksheet-detail', kwargs = self.kwargs_worksheet_full))
+        self.assertEqual(response.status_code, 200)
+
+    @override_settings(VALID_DOMAIN = ['testserver', ])
+    def test_WorksheetUpdateView(self):
+        """Tests updating worksheet without login."""
+
+        response = self.client.get(reverse(
+                'worksheet-update', kwargs = self.kwargs_worksheet_full))
+        self.assertEqual(response.status_code, 302)
+
+    @override_settings(VALID_DOMAIN = ['testserver', ])
+    def test_WorksheetUpdateView_with_login(self):
+        """Tests updating worksheet with login."""
+
+        status = self.client.login(username='sonlinux', password='password')
+        self.assertTrue(status)
+        response = self.client.get(reverse(
+            'worksheet-update', kwargs=self.kwargs_worksheet_full))
+        self.assertEqual(response.status_code, 200)
+        expected_templates = [
+            'update.html'
+        ]
+        self.assertEqual(response.template_name, expected_templates)
+
+    @override_settings(VALID_DOMAIN=['testserver', ])
+    def test_WorksheetModuleQuestionAnswers(self):
+
+        response = self.client.get(reverse('worksheet-module-answers',
+                                           kwargs=self.kwargs_worksheet_full))
+        self.assertEqual(response.status_code, 302)
+
+    @override_settings(VALID_DOMAIN = ['testserver', ])
+    def test_WorksheetModuleQuestionAnswers_with_login(self):
+
+        status = self.client.login(username='sonlinux', password='password')
+        self.assertTrue(status)
+
+        response = self.client.get(
+                reverse('worksheet-module-answers',
+                        kwargs = self.kwargs_worksheet_full))
+        self.assertEqual(response.status_code, 200)