示例#1
0
    def test_form_not_found_raise_exception(self):
        """
        Asserts that when looking up a form that does not exist
        """

        with self.assertRaises(SurveyFormNotFound):
            SurveyForm.get(self.test_survey_name)
 def test_create_form_with_malformed_html(self):
     """
     Make sure that if a SurveyForm is saved with unparseable html
     an exception is thrown
     """
     with self.assertRaises(ValidationError):
         SurveyForm.create('badform', '<input name="oops" /><<<>')
示例#3
0
 def test_create_form_with_malformed_html(self):
     """
     Make sure that if a SurveyForm is saved with unparseable html
     an exception is thrown
     """
     with self.assertRaises(ValidationError):
         SurveyForm.create('badform', '<input name="oops" /><<<>')
    def test_form_not_found_raise_exception(self):
        """
        Asserts that when looking up a form that does not exist
        """

        with self.assertRaises(SurveyFormNotFound):
            SurveyForm.get(self.test_survey_name)
示例#5
0
    def test_create_form_with_no_fields(self):
        """
        Make sure that if a SurveyForm is saved without any named fields
        an exception is thrown
        """
        with self.assertRaises(ValidationError):
            SurveyForm.create('badform', '<p>no input fields here</p>')

        with self.assertRaises(ValidationError):
            SurveyForm.create('badform', '<input id="input_without_name" />')
    def test_create_form_with_no_fields(self):
        """
        Make sure that if a SurveyForm is saved without any named fields
        an exception is thrown
        """
        with self.assertRaises(ValidationError):
            SurveyForm.create('badform', '<p>no input fields here</p>')

        with self.assertRaises(ValidationError):
            SurveyForm.create('badform', '<input id="input_without_name" />')
示例#7
0
    def test_create_form_update_existing(self):
        """
        Make sure we can update an existing form
        """
        survey = self._create_test_survey()
        self.assertIsNotNone(survey)

        survey = SurveyForm.create(self.test_survey_name, self.test_form_update, update_if_exists=True)
        self.assertIsNotNone(survey)

        survey = SurveyForm.get(self.test_survey_name)
        self.assertIsNotNone(survey)
        self.assertEquals(survey.form, self.test_form_update)
示例#8
0
def view_student_survey(user, survey_name, course=None, redirect_url=None, is_required=False, skip_redirect_url=None):
    """
    Shared utility method to render a survey form
    NOTE: This method is shared between the Survey and Courseware Djangoapps
    """

    redirect_url = redirect_url if redirect_url else reverse('dashboard')
    dashboard_redirect_url = reverse('dashboard')
    skip_redirect_url = skip_redirect_url if skip_redirect_url else dashboard_redirect_url

    survey = SurveyForm.get(survey_name, throw_if_not_found=False)
    if not survey:
        return HttpResponseRedirect(redirect_url)

    # the result set from get_answers, has an outer key with the user_id
    # just remove that outer key to make the JSON payload simplier
    existing_answers = survey.get_answers(user=user).get(user.id, {})

    platform_name = configuration_helpers.get_value('platform_name', settings.PLATFORM_NAME)

    context = {
        'existing_data_json': json.dumps(existing_answers),
        'postback_url': reverse('submit_answers', args=[survey_name]),
        'redirect_url': redirect_url,
        'skip_redirect_url': skip_redirect_url,
        'dashboard_redirect_url': dashboard_redirect_url,
        'survey_form': survey.form,
        'is_required': is_required,
        'mail_to_link': configuration_helpers.get_value('email_from_address', settings.CONTACT_EMAIL),
        'platform_name': platform_name,
        'course': course,
    }

    return render_to_response("survey/survey.html", context)
示例#9
0
    def setUp(self):
        """
        Set up the test data used in the specific tests
        """
        super(SurveyViewsTests, self).setUp()

        self.client = Client()

        # Create two accounts
        self.password = '******'
        self.student = User.objects.create_user('student', '*****@*****.**', self.password)

        self.test_survey_name = 'TestSurvey'
        self.test_form = '<input name="field1" /><input name="field2" /><select name="ddl"><option>1</option></select>'

        self.student_answers = OrderedDict({
            u'field1': u'value1',
            u'field2': u'value2',
            u'ddl': u'1',
        })

        self.course = CourseFactory.create(
            course_survey_required=True,
            course_survey_name=self.test_survey_name
        )

        self.survey = SurveyForm.create(self.test_survey_name, self.test_form)

        self.view_url = reverse('view_survey', args=[self.test_survey_name])
        self.postback_url = reverse('submit_answers', args=[self.test_survey_name])

        self.client.login(username=self.student.username, password=self.password)
示例#10
0
def check_survey_required_and_unanswered(user, course_descriptor):
    """
    Checks whether a user is required to answer the survey and has yet to do so.

    Returns:
        AccessResponse: Either ACCESS_GRANTED or SurveyRequiredAccessError.
    """

    if not is_survey_required_for_course(course_descriptor):
        return ACCESS_GRANTED

    # anonymous users do not need to answer the survey
    if user.is_anonymous:
        return ACCESS_GRANTED

    # course staff do not need to answer survey
    has_staff_access = has_access(user, 'staff', course_descriptor)
    if has_staff_access:
        return ACCESS_GRANTED

    # survey is required and it exists, let's see if user has answered the survey
    survey = SurveyForm.get(course_descriptor.course_survey_name)
    answered_survey = SurveyAnswer.do_survey_answers_exist(survey, user)
    if answered_survey:
        return ACCESS_GRANTED

    return SurveyRequiredAccessError()
示例#11
0
    def test_form_not_found_none(self):
        """
        Asserts that when looking up a form that does not exist
        """

        self.assertIsNone(
            SurveyForm.get(self.test_survey_name, throw_if_not_found=False))
    def setUp(self):
        """
        Set up the test data used in the specific tests
        """
        super(SurveyModelsTests, self).setUp()

        self.client = Client()

        # Create two accounts
        self.password = '******'
        self.student = User.objects.create_user('student', '*****@*****.**', self.password)
        self.student2 = User.objects.create_user('student2', '*****@*****.**', self.password)

        self.staff = User.objects.create_user('staff', '*****@*****.**', self.password)
        self.staff.is_staff = True
        self.staff.save()

        self.test_survey_name = 'TestSurvey'
        self.test_form = '<input name="foo"></input>'

        self.student_answers = OrderedDict({
            'field1': 'value1',
            'field2': 'value2',
        })

        self.student2_answers = OrderedDict({
            'field1': 'value3'
        })

        self.course = CourseFactory.create(
            course_survey_required=True,
            course_survey_name=self.test_survey_name
        )

        self.survey = SurveyForm.create(self.test_survey_name, self.test_form)
示例#13
0
def view_student_survey(user, survey_name, course=None, redirect_url=None, is_required=False, skip_redirect_url=None):
    """
    Shared utility method to render a survey form
    NOTE: This method is shared between the Survey and Courseware Djangoapps
    """

    redirect_url = redirect_url if redirect_url else reverse('dashboard')
    dashboard_redirect_url = reverse('dashboard')
    skip_redirect_url = skip_redirect_url if skip_redirect_url else dashboard_redirect_url

    survey = SurveyForm.get(survey_name, throw_if_not_found=False)
    if not survey:
        return HttpResponseRedirect(redirect_url)

    # the result set from get_answers, has an outer key with the user_id
    # just remove that outer key to make the JSON payload simplier
    existing_answers = survey.get_answers(user=user).get(user.id, {})

    platform_name = configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME)

    context = {
        'existing_data_json': json.dumps(existing_answers),
        'postback_url': reverse('submit_answers', args=[survey_name]),
        'redirect_url': redirect_url,
        'skip_redirect_url': skip_redirect_url,
        'dashboard_redirect_url': dashboard_redirect_url,
        'survey_form': survey.form,
        'is_required': is_required,
        'mail_to_link': configuration_helpers.get_value('email_from_address', settings.CONTACT_EMAIL),
        'platform_name': platform_name,
        'course': course,
    }

    return render_to_response("survey/survey.html", context)
示例#14
0
    def setUp(self):
        """
        Set up the test data used in the specific tests
        """
        self.client = Client()

        # Create two accounts
        self.password = '******'
        self.student = User.objects.create_user('student', '*****@*****.**',
                                                self.password)

        self.test_survey_name = 'TestSurvey'
        self.test_form = '<input name="field1" /><input name="field2" /><select name="ddl"><option>1</option></select>'

        self.student_answers = OrderedDict({
            u'field1': u'value1',
            u'field2': u'value2',
            u'ddl': u'1',
        })

        self.course = CourseFactory.create(
            course_survey_required=True,
            course_survey_name=self.test_survey_name)

        self.survey = SurveyForm.create(self.test_survey_name, self.test_form)

        self.view_url = reverse('view_survey', args=[self.test_survey_name])
        self.postback_url = reverse('submit_answers',
                                    args=[self.test_survey_name])

        self.client.login(username=self.student.username,
                          password=self.password)
示例#15
0
    def setUp(self):
        """
        Set up the test data used in the specific tests
        """
        super(SurveyViewsTests, self).setUp()

        self.test_form = '<input name="field1"></input>'
        self.survey = SurveyForm.create(self.test_survey_name, self.test_form)

        self.student_answers = OrderedDict({
            u'field1': u'value1',
            u'field2': u'value2',
        })

        # Create student accounts and activate them.
        for i in range(len(self.STUDENT_INFO)):
            email, password = self.STUDENT_INFO[i]
            username = '******'.format(i)
            self.create_account(username, email, password)
            self.activate_user(email)

        email, password = self.STUDENT_INFO[0]
        self.login(email, password)
        self.enroll(self.course, True)
        self.enroll(self.course_without_survey, True)
        self.enroll(self.course_with_bogus_survey, True)

        self.user = User.objects.get(email=email)

        self.view_url = reverse('view_survey', args=[self.test_survey_name])
        self.postback_url = reverse('submit_answers',
                                    args=[self.test_survey_name])
示例#16
0
    def setUp(self):
        """
        Set up the test data used in the specific tests
        """
        super(SurveyModelsTests, self).setUp()

        self.client = Client()

        # Create two accounts
        self.password = '******'
        self.student = User.objects.create_user('student', '*****@*****.**', self.password)
        self.student2 = User.objects.create_user('student2', '*****@*****.**', self.password)

        self.staff = User.objects.create_user('staff', '*****@*****.**', self.password)
        self.staff.is_staff = True
        self.staff.save()

        self.test_survey_name = 'TestSurvey'
        self.test_form = '<input name="foo"></input>'

        self.student_answers = OrderedDict({
            'field1': 'value1',
            'field2': 'value2',
        })

        self.student2_answers = OrderedDict({
            'field1': 'value3'
        })

        self.course = CourseFactory.create(
            course_survey_required=True,
            course_survey_name=self.test_survey_name
        )

        self.survey = SurveyForm.create(self.test_survey_name, self.test_form)
示例#17
0
    def setUp(self):
        """
        Set up the test data used in the specific tests
        """
        super(SurveyViewsTests, self).setUp()

        self.test_form = '<input name="field1"></input>'
        self.survey = SurveyForm.create(self.test_survey_name, self.test_form)

        self.student_answers = OrderedDict({
            u'field1': u'value1',
            u'field2': u'value2',
        })

        # Create student accounts and activate them.
        for i in range(len(self.STUDENT_INFO)):
            email, password = self.STUDENT_INFO[i]
            username = '******'.format(i)
            self.create_account(username, email, password)
            self.activate_user(email)

        email, password = self.STUDENT_INFO[0]
        self.login(email, password)
        self.enroll(self.course, True)
        self.enroll(self.course_without_survey, True)
        self.enroll(self.course_with_bogus_survey, True)

        self.user = User.objects.get(email=email)

        self.view_url = reverse('view_survey', args=[self.test_survey_name])
        self.postback_url = reverse('submit_answers', args=[self.test_survey_name])
示例#18
0
def view_student_survey(user, survey_name, course=None, redirect_url=None, is_required=False, skip_redirect_url=None):
    """
    Shared utility method to render a survey form
    NOTE: This method is shared between the Survey and Courseware Djangoapps
    """

    redirect_url = redirect_url if redirect_url else reverse("dashboard")
    dashboard_redirect_url = reverse("dashboard")
    skip_redirect_url = skip_redirect_url if skip_redirect_url else dashboard_redirect_url

    survey = SurveyForm.get(survey_name, throw_if_not_found=False)
    if not survey:
        return HttpResponseRedirect(redirect_url)

    # the result set from get_answers, has an outer key with the user_id
    # just remove that outer key to make the JSON payload simplier
    existing_answers = survey.get_answers(user=user).get(user.id, {})

    context = {
        "existing_data_json": json.dumps(existing_answers),
        "postback_url": reverse("submit_answers", args=[survey_name]),
        "redirect_url": redirect_url,
        "skip_redirect_url": skip_redirect_url,
        "dashboard_redirect_url": dashboard_redirect_url,
        "survey_form": survey.form,
        "is_required": is_required,
        "mail_to_link": microsite.get_value("email_from_address", settings.CONTACT_EMAIL),
        "course": course,
    }

    return render_to_response("survey/survey.html", context)
示例#19
0
def is_survey_required_for_course(course_descriptor):
    """
    Returns whether a Survey is required for this course
    """

    # check to see that the Survey name has been defined in the CourseDescriptor
    # and that the specified Survey exists

    return course_descriptor.course_survey_required and \
        SurveyForm.get(course_descriptor.course_survey_name, throw_if_not_found=False)
示例#20
0
def is_survey_required_for_course(course_descriptor):
    """
    Returns whether a Survey is required for this course
    """

    # check to see that the Survey name has been defined in the CourseDescriptor
    # and that the specified Survey exists

    return course_descriptor.course_survey_required and \
        SurveyForm.get(course_descriptor.course_survey_name, throw_if_not_found=False)
def manage_survey(request, survey_id=None):
    UserQuestionForm = user_question_form(request.user.id)
    SurveyQuestionFormset = inlineformset_factory(Survey, SurveyQuestion, form=UserQuestionForm)
    if survey_id is not None:
        survey = get_object_or_404(Survey, id__exact=int(survey_id))
        if survey.user != request.user:
            return HttpResponseForbidden()
    else:
        survey = None

    if request.POST:
        survey_form = SurveyForm(request.POST, instance=survey)
        if not survey_form.is_valid():
            messages.error(request, 'Please complete required fields.')
            return HttpResponseRedirect('/survey/create/')
        survey_instance = survey_form.save(commit=False)
        survey_instance.user_id = request.user.id
        survey_instance.save()

        survey_question_formset = SurveyQuestionFormset(request.POST, instance=survey)
        if survey_question_formset.is_valid():
            survey_question_instance = survey_question_formset.save(commit=False)
            for sqi in survey_question_instance:
                sqi.survey_id = survey_instance.id
                sqi.save()

        if survey_id is None:
            messages.success(request, 'New survey successfully created.')
        else:
            messages.success(request, 'Survey successfully updated.')

        return HttpResponseRedirect('/survey/')

    else:
        survey_form = SurveyForm(instance=survey)
        survey_question_formset = SurveyQuestionFormset(instance=survey)

        ctx = {
            'survey_form': survey_form,
            'survey_question_formset': survey_question_formset
        }
        return render(request, 'survey/manage_survey.html', ctx)
示例#22
0
    def test_create_new_form(self):
        """
        Make sure we can create a new form a look it up
        """

        survey = self._create_test_survey()
        self.assertIsNotNone(survey)

        new_survey = SurveyForm.get(self.test_survey_name)
        self.assertIsNotNone(new_survey)
        self.assertEqual(new_survey.form, self.test_form)
示例#23
0
def is_survey_required_for_course(course_descriptor):
    """
    Returns whether a Survey is required for this course
    """

    # Check to see that the survey is required in the CourseDescriptor.
    if not getattr(course_descriptor, 'course_survey_required', False):
        return SurveyRequiredAccessError()

    # Check that the specified Survey for the course exists.
    return SurveyForm.get(course_descriptor.course_survey_name, throw_if_not_found=False)
示例#24
0
def is_survey_required_for_course(course_descriptor):
    """
    Returns whether a Survey is required for this course
    """

    # Check to see that the survey is required in the CourseDescriptor.
    if not getattr(course_descriptor, 'course_survey_required', False):
        return False

    # Check that the specified Survey for the course exists.
    return SurveyForm.get(course_descriptor.course_survey_name, throw_if_not_found=False)
示例#25
0
    def test_create_new_form(self):
        """
        Make sure we can create a new form a look it up
        """

        survey = self._create_test_survey()
        self.assertIsNotNone(survey)

        new_survey = SurveyForm.get(self.test_survey_name)
        self.assertIsNotNone(new_survey)
        self.assertEqual(new_survey.form, self.test_form)
示例#26
0
def submit_answers(request, survey_name):
    """
    Form submission post-back endpoint.

    NOTE: We do not have a formal definition of a Survey Form, it's just some authored HTML
    form fields (via Django Admin site). Therefore we do not do any validation of the submission server side. It is
    assumed that all validation is done via JavaScript in the survey.html file
    """
    survey = SurveyForm.get(survey_name, throw_if_not_found=False)

    if not survey:
        return HttpResponseNotFound()

    answers = {}
    for key in request.POST.keys():
        # support multi-SELECT form values, by string concatenating them with a comma separator
        array_val = request.POST.getlist(key)
        answers[key] = request.POST[key] if len(array_val) == 0 else ','.join(
            array_val)

    # the URL we are supposed to redirect to is
    # in a hidden form field
    redirect_url = answers[
        '_redirect_url'] if '_redirect_url' in answers else reverse(
            'dashboard')

    course_key = CourseKey.from_string(
        answers['course_id']) if 'course_id' in answers else None

    allowed_field_names = survey.get_field_names()

    # scrub the answers to make sure nothing malicious from the user gets stored in
    # our database, e.g. JavaScript
    filtered_answers = {}
    for answer_key in answers.keys():
        # only allow known input fields
        if answer_key in allowed_field_names:
            filtered_answers[answer_key] = escape(answers[answer_key])

    survey.save_user_answers(request.user, filtered_answers, course_key)

    response_params = json.dumps({
        # The HTTP end-point for the payment processor.
        "redirect_url": redirect_url,
    })

    return HttpResponse(response_params, content_type="text/json")
示例#27
0
文件: utils.py 项目: ahmadiga/min_edx
def must_answer_survey(course_descriptor, user):
    """
    Returns whether a user needs to answer a required survey
    """
    if not is_survey_required_for_course(course_descriptor):
        return False

    # this will throw exception if not found, but a non existing survey name will
    # be trapped in the above is_survey_required_for_course() method
    survey = SurveyForm.get(course_descriptor.course_survey_name)

    has_staff_access = has_access(user, "staff", course_descriptor)

    # survey is required and it exists, let's see if user has answered the survey
    # course staff do not need to answer survey
    answered_survey = SurveyAnswer.do_survey_answers_exist(survey, user)
    return not answered_survey and not has_staff_access
示例#28
0
def must_answer_survey(course_descriptor, user):
    """
    Returns whether a user needs to answer a required survey
    """
    if not is_survey_required_for_course(course_descriptor):
        return False

    # this will throw exception if not found, but a non existing survey name will
    # be trapped in the above is_survey_required_for_course() method
    survey = SurveyForm.get(course_descriptor.course_survey_name)

    has_staff_access = has_access(user, 'staff', course_descriptor)

    # survey is required and it exists, let's see if user has answered the survey
    # course staff do not need to answer survey
    answered_survey = SurveyAnswer.do_survey_answers_exist(survey, user)
    return not answered_survey and not has_staff_access
示例#29
0
    def setUp(self):
        """
        Set up the test data used in the specific tests
        """
        super(SurveyViewsTests, self).setUp()

        self.test_survey_name = 'TestSurvey'
        self.test_form = '<input name="field1"></input>'

        self.survey = SurveyForm.create(self.test_survey_name, self.test_form)

        self.student_answers = OrderedDict({
            u'field1': u'value1',
            u'field2': u'value2',
        })

        self.course = CourseFactory.create(
            display_name='<script>alert("XSS")</script>',
            course_survey_required=True,
            course_survey_name=self.test_survey_name
        )

        self.course_with_bogus_survey = CourseFactory.create(
            course_survey_required=True,
            course_survey_name="DoesNotExist"
        )

        self.course_without_survey = CourseFactory.create()

        # Create student accounts and activate them.
        for i in range(len(self.STUDENT_INFO)):
            email, password = self.STUDENT_INFO[i]
            username = '******'.format(i)
            self.create_account(username, email, password)
            self.activate_user(email)

        email, password = self.STUDENT_INFO[0]
        self.login(email, password)
        self.enroll(self.course, True)
        self.enroll(self.course_without_survey, True)
        self.enroll(self.course_with_bogus_survey, True)

        self.view_url = reverse('view_survey', args=[self.test_survey_name])
        self.postback_url = reverse('submit_answers', args=[self.test_survey_name])
示例#30
0
    def setUp(self):
        """
        Set up the test data used in the specific tests
        """
        super(SurveyViewsTests, self).setUp()

        self.test_survey_name = 'TestSurvey'
        self.test_form = '<input name="field1"></input>'

        self.survey = SurveyForm.create(self.test_survey_name, self.test_form)

        self.student_answers = OrderedDict({
            u'field1': u'value1',
            u'field2': u'value2',
        })

        self.course = CourseFactory.create(
            display_name='<script>alert("XSS")</script>',
            course_survey_required=True,
            course_survey_name=self.test_survey_name
        )

        self.course_with_bogus_survey = CourseFactory.create(
            course_survey_required=True,
            course_survey_name="DoesNotExist"
        )

        self.course_without_survey = CourseFactory.create()

        # Create student accounts and activate them.
        for i in range(len(self.STUDENT_INFO)):
            email, password = self.STUDENT_INFO[i]
            username = '******'.format(i)
            self.create_account(username, email, password)
            self.activate_user(email)

        email, password = self.STUDENT_INFO[0]
        self.login(email, password)
        self.enroll(self.course, True)
        self.enroll(self.course_without_survey, True)
        self.enroll(self.course_with_bogus_survey, True)

        self.view_url = reverse('view_survey', args=[self.test_survey_name])
        self.postback_url = reverse('submit_answers', args=[self.test_survey_name])
示例#31
0
def submit_answers(request, survey_name):
    """
    Form submission post-back endpoint.

    NOTE: We do not have a formal definition of a Survey Form, it's just some authored HTML
    form fields (via Django Admin site). Therefore we do not do any validation of the submission server side. It is
    assumed that all validation is done via JavaScript in the survey.html file
    """
    survey = SurveyForm.get(survey_name, throw_if_not_found=False)

    if not survey:
        return HttpResponseNotFound()

    answers = {}
    for key in request.POST.keys():
        # support multi-SELECT form values, by string concatenating them with a comma separator
        array_val = request.POST.getlist(key)
        answers[key] = request.POST[key] if len(array_val) == 0 else ','.join(array_val)

    # the URL we are supposed to redirect to is
    # in a hidden form field
    redirect_url = answers['_redirect_url'] if '_redirect_url' in answers else reverse('dashboard')

    course_key = CourseKey.from_string(answers['course_id']) if 'course_id' in answers else None

    allowed_field_names = survey.get_field_names()

    # scrub the answers to make sure nothing malicious from the user gets stored in
    # our database, e.g. JavaScript
    filtered_answers = {}
    for answer_key in answers.keys():
        # only allow known input fields
        if answer_key in allowed_field_names:
            filtered_answers[answer_key] = escape(answers[answer_key])

    survey.save_user_answers(request.user, filtered_answers, course_key)

    response_params = json.dumps({
        # The HTTP end-point for the payment processor.
        "redirect_url": redirect_url,
    })

    return HttpResponse(response_params, content_type="text/json")
示例#32
0
def is_survey_required_and_unanswered(user, course_descriptor):
    """
    Returns whether a user is required to answer the survey and has yet to do so.
    """

    if not is_survey_required_for_course(course_descriptor):
        return False

    # anonymous users do not need to answer the survey
    if user.is_anonymous:
        return False

    # course staff do not need to answer survey
    has_staff_access = has_access(user, 'staff', course_descriptor)
    if has_staff_access:
        return False

    # survey is required and it exists, let's see if user has answered the survey
    survey = SurveyForm.get(course_descriptor.course_survey_name)
    answered_survey = SurveyAnswer.do_survey_answers_exist(survey, user)
    if not answered_survey:
        return True
示例#33
0
def is_survey_required_and_unanswered(user, course_descriptor):
    """
    Returns whether a user is required to answer the survey and has yet to do so.
    """

    if not is_survey_required_for_course(course_descriptor):
        return False

    # anonymous users do not need to answer the survey
    if user.is_anonymous():
        return False

    # course staff do not need to answer survey
    has_staff_access = has_access(user, 'staff', course_descriptor)
    if has_staff_access:
        return False

    # survey is required and it exists, let's see if user has answered the survey
    survey = SurveyForm.get(course_descriptor.course_survey_name)
    answered_survey = SurveyAnswer.do_survey_answers_exist(survey, user)
    if not answered_survey:
        return True
示例#34
0
def manage_survey(request, survey_id=None):
    UserQuestionForm = user_question_form(request.user.id)
    SurveyQuestionFormset = inlineformset_factory(Survey,
                                                  SurveyQuestion,
                                                  form=UserQuestionForm)
    if survey_id is not None:
        survey = get_object_or_404(Survey, id__exact=int(survey_id))
        if survey.user != request.user:
            return HttpResponseForbidden()
    else:
        survey = None

    if request.POST:
        survey_form = SurveyForm(request.POST, instance=survey)
        if not survey_form.is_valid():
            messages.error(request, 'Please complete required fields.')
            return HttpResponseRedirect('/survey/create/')
        survey_instance = survey_form.save(commit=False)
        survey_instance.user_id = request.user.id
        survey_instance.save()

        survey_question_formset = SurveyQuestionFormset(request.POST,
                                                        instance=survey)
        if survey_question_formset.is_valid():
            survey_question_instance = survey_question_formset.save(
                commit=False)
            for sqi in survey_question_instance:
                sqi.survey_id = survey_instance.id
                sqi.save()

        if survey_id is None:
            messages.success(request, 'New survey successfully created.')
        else:
            messages.success(request, 'Survey successfully updated.')

        return HttpResponseRedirect('/survey/')

    else:
        survey_form = SurveyForm(instance=survey)
        survey_question_formset = SurveyQuestionFormset(instance=survey)

        ctx = {
            'survey_form': survey_form,
            'survey_question_formset': survey_question_formset
        }
        return render(request, 'survey/manage_survey.html', ctx)
示例#35
0
 def clean_form(self):
     """Validate the HTML template."""
     form = self.cleaned_data["form"]
     SurveyForm.validate_form_html(form)
     return form
示例#36
0
 def _create_test_survey(self):
     """
     Helper method to set up test form
     """
     return SurveyForm.create(self.test_survey_name, self.test_form)
示例#37
0
 def _create_test_survey(self):
     """
     Helper method to set up test form
     """
     return SurveyForm.create(self.test_survey_name, self.test_form)
示例#38
0
    def test_form_not_found_none(self):
        """
        Asserts that when looking up a form that does not exist
        """

        self.assertIsNone(SurveyForm.get(self.test_survey_name, throw_if_not_found=False))
示例#39
0
 def clean_form(self):
     """Validate the HTML template."""
     form = self.cleaned_data["form"]
     SurveyForm.validate_form_html(form)
     return form