Python django.http.HttpRequest() Examples

The following are 30 code examples for showing how to use django.http.HttpRequest(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: py2swagger   Author: Arello-Mobile   File: method.py    License: MIT License 6 votes vote down vote up
def _create_view(self):
        """
        Creates DjangoRestFramework view
        :return: view
        """
        view = self.callback()

        view.kwargs = getattr(view, 'kwargs', dict())
        if hasattr(self.introspector.pattern, 'default_args'):
            view.kwargs.update(self.introspector.pattern.default_args)

        view.request = HttpRequest()
        view.request.user = AnonymousUser()
        view.request.method = self.method

        return view 
Example 2
Project: py2swagger   Author: Arello-Mobile   File: test_serializer_introspector.py    License: MIT License 6 votes vote down vote up
def test_default_serializer(self):
        if StrictVersion(VERSION) >= StrictVersion('3.0.0'):
            return

        from rest_framework.viewsets import ModelViewSet
        from django.http import HttpRequest
        from testapp.models import TestModel

        class TestViewSet(ModelViewSet):
            model = TestModel

        view = TestViewSet()
        view.request = HttpRequest()

        si = SerializerIntrospector(view.get_serializer_class())

        self.assertEqual(si.name, 'TestModelSerializer') 
Example 3
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def index(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
    role = request.member.role
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)

    if role in ['INST', 'TA']:
        quiz = Quiz.objects.filter(activity=activity).first()  # will be None if no quiz created for this activity
        if not quiz:
            # no quiz created? Only option is to create.
            return redirect('offering:quiz:edit', course_slug=course_slug, activity_slug=activity_slug)
        return _index_instructor(request, offering, activity, quiz)

    elif role == 'STUD':
        quiz = get_object_or_404(Quiz, activity=activity)  # will 404 if no quiz created for this activity
        return _index_student(request, offering, activity, quiz)

    else:
        raise Http404() 
Example 4
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def instructions(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    quiz = get_object_or_404(Quiz, activity=activity)

    start, end = quiz.get_start_end(member=request.member)
    now = datetime.datetime.now()

    if now > end:
        return ForbiddenResponse(request, 'quiz is completed.')

    context = {
        'offering': offering,
        'activity': activity,
        'quiz': quiz,
        'is_staff': request.member.role in ['INST', 'TA'],
        'start': start,
        'end': end,
    }
    return render(request, 'quizzes/instructions.html', context=context) 
Example 5
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def question_add(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    quiz = get_object_or_404(Quiz, activity=activity)

    if quiz.completed():
        return ForbiddenResponse(request, 'quiz is completed. You cannot edit questions after the end of the quiz time')

    if request.method == 'GET' and 'type' not in request.GET:
        # ask for type of question
        context = {
            'offering': offering,
            'activity': activity,
            'quiz': quiz,
            'question_type_choices': QUESTION_TYPE_CHOICES,
        }
        return render(request, 'quizzes/question_type.html', context=context)

    return _question_edit(request, offering, activity, quiz, question=None, version=None) 
Example 6
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def version_delete(request: HttpRequest, course_slug: str, activity_slug: str, question_id: str, version_id: str) -> HttpResponse:
    if request.method in ['POST', 'DELETE']:
        quiz = get_object_or_404(Quiz, activity__slug=activity_slug, activity__offering__slug=course_slug)
        if quiz.completed():
            return ForbiddenResponse(request, 'Quiz is completed. You cannot modify questions after the end of the quiz time')
        question = get_object_or_404(Question, quiz=quiz, id=question_id)
        version = get_object_or_404(QuestionVersion, question=question, id=version_id)
        other_versions = QuestionVersion.objects.filter(question=question).exclude(id=version_id)
        if not other_versions.exists():
            messages.add_message(request, messages.ERROR, 'Cannot delete the only version of a question.')
            return redirect('offering:quiz:question_edit', course_slug=course_slug, activity_slug=activity_slug, question_id=question_id, version_id=version_id)
        version.status = 'D'
        version.save()
        messages.add_message(request, messages.SUCCESS, 'Question version deleted.')
        LogEntry(userid=request.user.username, description='deleted quiz question version id=%i' % (question.id,),
                 related_object=question).save()
        return redirect('offering:quiz:index', course_slug=course_slug, activity_slug=activity_slug)
    else:
        return HttpError(request, status=405, title="Method Not Allowed", error='POST or DELETE requests only.') 
Example 7
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def submissions(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    quiz = get_object_or_404(Quiz, activity=activity)
    questions = Question.objects.filter(quiz=quiz)

    answers = QuestionAnswer.objects.filter(question__in=questions) \
        .select_related('student__person') \
        .order_by('student__person')

    students = set(a.student for a in answers)
    starts_ends = quiz.get_starts_ends(students)
    by_student = itertools.groupby(answers, key=lambda a: a.student)
    subs_late = [(member, max(a.modified_at for a in ans) - starts_ends[member][1]) for member, ans in by_student]

    context = {
        'offering': offering,
        'activity': activity,
        'quiz': quiz,
        'subs_late': subs_late,
        'timedelta_zero': datetime.timedelta(seconds=0)
    }
    return render(request, 'quizzes/submissions.html', context=context) 
Example 8
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _setup_download(request: HttpRequest, course_slug: str, activity_slug: str):
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    quiz = get_object_or_404(Quiz, activity=activity)
    questions = Question.objects.filter(quiz=quiz)
    versions = QuestionVersion.objects.filter(question__in=questions)
    version_number_lookup = {  # version_number_lookup[question_id][version_id] == version_number
        q_id: {v.id: i+1 for i,v in enumerate(vs)}
        for q_id, vs in itertools.groupby(versions, key=lambda v: v.question_id)
    }

    answers = QuestionAnswer.objects.filter(question__in=questions) \
        .select_related('student__person', 'question_version', 'question') \
        .order_by('student__person')

    by_student = itertools.groupby(answers, key=lambda a: a.student)
    multiple_versions = len(questions) != len(versions)

    return activity, questions, version_number_lookup, by_student, multiple_versions 
Example 9
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def submitted_file(request: HttpRequest, course_slug: str, activity_slug: str, userid: str, answer_id: str, secret: str) -> StreamingHttpResponse:
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    member = get_object_or_404(Member, ~Q(role='DROP'), find_member(userid), offering__slug=course_slug)
    answer = get_object_or_404(QuestionAnswer, question__quiz__activity=activity, student=member, id=answer_id)

    real_secret = answer.answer['data'].get('secret', '?')
    if real_secret != '?' and secret == real_secret:
        return _return_submitted_file(answer.answer['data'], answer.file.open('rb'))

    else:
        # It's not the current submission, but an instructor looking at history might be trying to find an old one...
        submissions = QuizSubmission.objects.filter(quiz__activity=activity, student=member)
        for qs in submissions:
            for answer_config in qs.config['answers']:
                version_id, answer_id, a = answer_config
                if not isinstance(a['data'], dict):
                    continue
                real_secret = a['data'].get('secret', '?')
                if answer.question_version_id == version_id and answer.id == answer_id and real_secret != '?' and secret == real_secret:
                    # aha! Temporarily replace answer.file with the old version (without saving) so we can return it
                    answer.file = a['filepath']
                    return _return_submitted_file(a['data'], answer.file.open('rb'))

    raise Http404() 
Example 10
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def submission_history(request: HttpRequest, course_slug: str, activity_slug: str, userid: str) -> HttpResponse:
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    quiz = get_object_or_404(Quiz, activity=activity)
    questions = Question.objects.filter(quiz=quiz)
    versions = QuestionVersion.objects.filter(question__in=questions)
    member = get_object_or_404(Member, ~Q(role='DROP'), find_member(userid), offering__slug=course_slug)
    quiz_submissions = QuizSubmission.objects.filter(quiz=quiz, student=member)
    [qs.annotate_questions(questions, versions) for qs in quiz_submissions]

    context = {
        'offering': offering,
        'activity': activity,
        'quiz': quiz,
        'member': member,
        'quiz_submissions': quiz_submissions,
        'can_photo': has_photo_agreement(request.member.person)
    }
    return render(request, 'quizzes/submission_history.html', context=context) 
Example 11
Project: trove-dashboard   Author: openstack   File: tests.py    License: Apache License 2.0 6 votes vote down vote up
def test_master_list_pagination(self):
        request = http.HttpRequest()

        first_part = common.Paginated(items=self.databases.list()[:1],
                                      next_marker='marker')
        second_part = common.Paginated(items=self.databases.list()[1:])

        self.mock_instance_list.side_effect = [
            first_part, second_part, first_part]

        advanced_page = create_instance.AdvancedAction(request, None)
        choices = advanced_page.populate_master_choices(request, None)
        expected_calls = [
            mock.call(request),
            mock.call(request, marker='marker'),
            mock.call(request)]
        self.assertEqual(expected_calls,
                         self.mock_instance_list.call_args_list)
        self.assertTrue(len(choices) == len(self.databases.list()) + 1) 
Example 12
Project: arches   Author: archesproject   File: tile_model_tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_user_owns_provisional(self):
        """
        Tests that a user is the owner of a provisional edit

        """

        json = {
            "resourceinstance_id": "40000000-0000-0000-0000-000000000000",
            "parenttile_id": "",
            "nodegroup_id": "72048cb3-adbc-11e6-9ccf-14109fd34195",
            "tileid": "",
            "data": {"72048cb3-adbc-11e6-9ccf-14109fd34195": "TEST 1"},
        }

        user = User.objects.create_user(username="testuser", password="TestingTesting123!")
        provisional_tile = Tile(json)
        request = HttpRequest()
        request.user = user
        provisional_tile.save(index=False, request=request)

        self.assertEqual(provisional_tile.user_owns_provisional(user), True) 
Example 13
Project: PrivacyScore   Author: PrivacyScore   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def scan_scan_list(request: HttpRequest, scan_list_id: int) -> HttpResponse:
    """Schedule the scan of a scan list."""
    scan_list = get_object_or_404(
        ScanList.objects.prefetch_related(Prefetch(
            'sites',
            queryset=Site.objects.select_related('last_scan') \
                .annotate_most_recent_scan_start() \
                .annotate_most_recent_scan_end_or_null())
        ), pk=scan_list_id)
    was_any_site_scannable = scan_list.scan()
    if was_any_site_scannable:
        num_scanning_sites = Scan.objects.filter(end__isnull=True).count()
        messages.success(request,
            _("Scans for this list have been scheduled. "+ \
              "The total number of sites in the scanning queue "+ \
              "is %i (including yours)." % num_scanning_sites))
    else:
        messages.warning(request,
            _('All sites have been scanned recently. Please wait 30 minutes and try again.'))

    return redirect(reverse('frontend:view_scan_list', args=(scan_list_id,))) 
Example 14
Project: PrivacyScore   Author: PrivacyScore   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def faq(request: HttpRequest):
    num_scans  = Site.objects.filter(scans__isnull=False).count()
    num_scanning_sites = Scan.objects.filter(end__isnull=True).count()

    # query = '''SELECT
    #     COUNT(jsonb_array_length("result"->'leaks'))
    #     FROM backend_scanresult
    #     WHERE backend_scanresult.scan_id IN (
    #         SELECT backend_site.last_scan_id
    #         FROM backend_site
    #         WHERE backend_site.last_scan_id IS NOT NULL)
    #     AND jsonb_array_length("result"->'leaks') > 0'''
    # 
    # with connection.cursor() as cursor:
    #     cursor.execute(query)
    #     num_sites_failing_serverleak = cursor.fetchone()[0]
        
    return render(request, 'frontend/faq.html', {
        'num_scanning_sites': num_scanning_sites,
        'num_scans':  num_scans,
        'num_sites': Site.objects.count(),
        # 'num_sites_failing_serverleak': num_sites_failing_serverleak
    }) 
Example 15
Project: django-defender   Author: jazzband   File: tests.py    License: Apache License 2.0 6 votes vote down vote up
def test_get_ip_address_from_request(self):
        """ get ip from request, make sure it is correct """
        req = HttpRequest()
        req.META["REMOTE_ADDR"] = "1.2.3.4"
        ip = utils.get_ip_address_from_request(req)
        self.assertEqual(ip, "1.2.3.4")

        req = HttpRequest()
        req.META["REMOTE_ADDR"] = "1.2.3.4 "
        ip = utils.get_ip_address_from_request(req)
        self.assertEqual(ip, "1.2.3.4")

        req = HttpRequest()
        req.META["REMOTE_ADDR"] = "192.168.100.34.y"
        ip = utils.get_ip_address_from_request(req)
        self.assertEqual(ip, "127.0.0.1")

        req = HttpRequest()
        req.META["REMOTE_ADDR"] = "cat"
        ip = utils.get_ip_address_from_request(req)
        self.assertEqual(ip, "127.0.0.1")

        req = HttpRequest()
        ip = utils.get_ip_address_from_request(req)
        self.assertEqual(ip, "127.0.0.1") 
Example 16
Project: django-defender   Author: jazzband   File: tests.py    License: Apache License 2.0 6 votes vote down vote up
def test_get_user_attempts(self):
        """ Get the user attempts make sure they are correct """
        ip_attempts = random.randint(3, 12)
        username_attempts = random.randint(3, 12)
        for i in range(0, ip_attempts):
            utils.increment_key(utils.get_ip_attempt_cache_key("1.2.3.4"))
        for i in range(0, username_attempts):
            utils.increment_key(utils.get_username_attempt_cache_key("foobar"))
        req = HttpRequest()
        req.POST["username"] = "foobar"
        req.META["HTTP_X_REAL_IP"] = "1.2.3.4"
        self.assertEqual(
            utils.get_user_attempts(req), max(ip_attempts, username_attempts)
        )

        req = HttpRequest()
        req.POST["username"] = "foobar"
        req.META["HTTP_X_REAL_IP"] = "5.6.7.8"
        self.assertEqual(utils.get_user_attempts(req), username_attempts)

        req = HttpRequest()
        req.POST["username"] = "barfoo"
        req.META["HTTP_X_REAL_IP"] = "1.2.3.4"
        self.assertEqual(utils.get_user_attempts(req), ip_attempts) 
Example 17
Project: GTDWeb   Author: lanbing510   File: client.py    License: GNU General Public License v2.0 6 votes vote down vote up
def logout(self):
        """
        Removes the authenticated user's cookies and session object.

        Causes the authenticated user to be logged out.
        """
        from django.contrib.auth import get_user, logout

        request = HttpRequest()
        engine = import_module(settings.SESSION_ENGINE)
        if self.session:
            request.session = self.session
            request.user = get_user(request)
        else:
            request.session = engine.SessionStore()
        logout(request)
        self.cookies = SimpleCookie() 
Example 18
Project: Servo   Author: fpsw   File: test_unit.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_homepage_error_without_cookies(self):
        request = HttpRequest()
        response = checkin.home(request)
        self.assertTrue(response.content.startswith("<!DOCTYPE html>"), response.content)
        self.assertIn('<title>An error occurred', response.content)
        self.assertTrue(response.content.endswith('</html>')) 
Example 19
Project: polls-api   Author: apiaryio   File: tests.py    License: MIT License 5 votes vote down vote up
def test_json_includes_allow_header(self):
        class TestAllowActionResource(Resource):
            def get_actions(self):
                return { 'delete': Action(method='DELETE', attributes=None) }

        request = HttpRequest()
        request.META['HTTP_ACCEPT'] = 'application/json'
        response = TestAllowActionResource().get(request)

        self.assertEqual(response['Allow'], 'HEAD, GET, DELETE') 
Example 20
Project: polls-api   Author: apiaryio   File: tests.py    License: MIT License 5 votes vote down vote up
def test_invalid_accept_header(self):
        class TestResource(Resource):
            pass

        request = HttpRequest()
        request.META['HTTP_ACCEPT'] = 'application'
        response = TestResource().get(request)

        self.assertEqual(response.status_code, 200) 
Example 21
def test_request(self):
        """ Makes sure that the request has correct `usersettings` attribute. """
        middleware = CurrentUserSettingsMiddleware()
        request = HttpRequest()
        middleware.process_request(request)
        self.assertEqual(request.usersettings.site.id, settings.SITE_ID) 
Example 22
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _index_instructor(request: HttpRequest, offering: CourseOffering, activity: Activity, quiz: Quiz) -> HttpResponse:
    assert request.member.role in ['INST', 'TA']
    questions = Question.objects.filter(quiz=quiz)

    context = {
        'offering': offering,
        'activity': activity,
        'quiz': quiz,
        'questions': questions,
    }
    return render(request, 'quizzes/index_staff.html', context=context) 
Example 23
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _student_review(request: HttpRequest, offering: CourseOffering, activity: Activity, quiz: Quiz) -> HttpResponse:
    member = request.member
    assert member.role == 'STUD'

    questions = Question.objects.filter(quiz=quiz)
    answers = QuestionAnswer.objects.filter(student=member, question__in=questions).select_related('question')
    versions = QuestionVersion.select(quiz=quiz, questions=questions, student=member, answers=answers)
    activity_mark = get_activity_mark_for_student(activity, member)
    component_lookup = quiz.activitycomponents_by_question()
    if activity_mark:
        comp_marks = ActivityComponentMark.objects.filter(activity_mark=activity_mark).select_related('activity_component')
        comp_mark_lookup = {acm.activity_component_id: acm for acm in comp_marks}
        mark_lookup = {}
        for q in questions:
            comp = component_lookup.get(q)
            if not comp:
                continue
            acm = comp_mark_lookup.get(comp.id)
            mark_lookup[q.id] = acm
    else:
        mark_lookup = {}

    answer_lookup = {a.question_id: a for a in answers}
    version_answers = [(v, answer_lookup.get(v.question.id, None), mark_lookup.get(v.question_id, None)) for v in versions]
    total_marks = sum(q.points for q in questions)

    context = {
        'offering': offering,
        'activity': activity,
        'quiz': quiz,
        'activity_mark': activity_mark,
        'version_answers': version_answers,
        'total_marks': total_marks,
    }
    return render(request, 'quizzes/student_review.html', context=context) 
Example 24
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def preview_student(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
    """
    Instructor's preview of what students will see
    """
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    quiz = get_object_or_404(Quiz, activity=activity)
    questions = Question.objects.filter(quiz=quiz)
    versions = QuestionVersion.select(quiz=quiz, questions=questions, student=None, answers=None)

    fields = OrderedDict((v.question.ident(), v.entry_field(student=None)) for i, v in enumerate(versions))
    form = StudentForm()
    form.fields = fields

    question_data = list(zip(questions, versions, form.visible_fields()))
    start, end = quiz.get_start_end(member=None)
    seconds_left = (end - datetime.datetime.now()).total_seconds()
    context = {
        'offering': offering,
        'activity': activity,
        'quiz': quiz,
        'questions': questions,
        'question_data': question_data,
        'preview': True,
        'start': start,
        'end': end,
        'seconds_left': seconds_left if seconds_left>0 else 0,
    }
    return render(request, 'quizzes/index_student.html', context=context) 
Example 25
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def export(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    quiz = get_object_or_404(Quiz, activity=activity)

    data = quiz.export()
    resp = JsonResponse(data, json_dumps_params={'indent': 2})
    resp['Content-Disposition'] = 'attachment; filename="%s-quiz.json"' % (activity.slug,)
    return resp 
Example 26
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def question_edit(request: HttpRequest, course_slug: str, activity_slug: str, question_id: str, version_id: str) -> HttpResponse:
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    quiz = get_object_or_404(Quiz, activity=activity)
    question = get_object_or_404(Question, quiz=quiz, id=question_id)
    version = get_object_or_404(QuestionVersion.objects.select_related('question'), question=question, id=version_id)

    #if quiz.completed():
    #    return ForbiddenResponse(request, 'quiz is completed. You cannot edit questions after the end of the quiz time')

    return _question_edit(request, offering, activity, quiz, question, version) 
Example 27
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def question_add_version(request: HttpRequest, course_slug: str, activity_slug: str, question_id: str) -> HttpResponse:
    offering = get_object_or_404(CourseOffering, slug=course_slug)
    activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False)
    quiz = get_object_or_404(Quiz, activity=activity)
    question = get_object_or_404(Question, quiz=quiz, id=question_id)

    if quiz.completed():
        return ForbiddenResponse(request, 'quiz is completed. You cannot edit questions after the end of the quiz time')

    return _question_edit(request, offering, activity, quiz, question, version=None) 
Example 28
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def question_reorder(request: HttpRequest, course_slug: str, activity_slug: str, question_id: str) -> HttpResponse:
    quiz = get_object_or_404(Quiz, activity__slug=activity_slug, activity__offering__slug=course_slug)
    question1 = get_object_or_404(Question, quiz=quiz, id=question_id)

    direction = request.GET.get('direction', '')
    if direction not in ['up', 'down']:
        raise Http404()

    #if quiz.completed():
    #    return ForbiddenResponse(request, 'Quiz is completed. You cannot modify questions after the end of the quiz time')

    try:
        if direction == 'up':
            # find question before this one
            prev_order = Question.objects.filter(quiz=quiz, order__lt=question1.order).aggregate(Max('order'))['order__max']
            question2 = Question.objects.get(quiz=quiz, order=prev_order)
        else:
            # find question after this one
            next_order = Question.objects.filter(quiz=quiz, order__gt=question1.order).aggregate(Min('order'))['order__min']
            question2 = Question.objects.get(quiz=quiz, order=next_order)

    except Question.DoesNotExist:
        # moving up past the start, or down past the end: ignore
        pass

    else:
        o1 = question1.order
        o2 = question2.order
        with transaction.atomic():
            question2.order = o1
            question2.save()
            question1.order = o2
            question1.save()
            if quiz.activity.quiz_marking():
                # configured for quiz-based marking: update that so the order matches
                quiz.configure_marking(delete_others=False)
                messages.add_message(request, messages.INFO, 'Reordered marking rubric to match quiz questions.')

    return HttpResponseRedirect(resolve_url('offering:quiz:index', course_slug=course_slug, activity_slug=activity_slug)
                                + '#q-' + str(question1.id)) 
Example 29
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def download_submissions(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
    activity, questions, version_number_lookup, by_student, multiple_versions = _setup_download(request, course_slug, activity_slug)

    data = []
    for m, answers in by_student:
        answers = list(answers)
        answers_lookup = {a.question_id: a for a in answers}
        lastmod = max(a.modified_at for a in answers)
        d = {
            'userid': m.person.userid_or_emplid(),
            'last_submission': lastmod,
        }
        d.update({
            'q-%i'%(i+1):
                (
                    {
                        'version': version_number_lookup[q.id].get(answers_lookup[q.id].question_version_id, 0),
                        'answer': answers_lookup[q.id].question_version.helper(question=q).to_text(answers_lookup[q.id])
                    }
                    if q.id in answers_lookup else None
                )
            for i, q in enumerate(questions)
        })
        # The .get(...version_id, 0) returns 0 if a student answers a version, then the instructor deletes it. Hopefully never
        data.append(d)

    response = JsonResponse({'submissions': data})
    response['Content-Disposition'] = 'inline; filename="%s-results.json"' % (activity.slug,)
    return response 
Example 30
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def download_submissions_csv(request: HttpRequest, course_slug: str, activity_slug: str) -> HttpResponse:
    activity, questions, version_number_lookup, by_student, multiple_versions = _setup_download(request, course_slug, activity_slug)
    response = HttpResponse(content_type='text/csv; charset=utf-8')
    response['Content-Disposition'] = 'inline; filename="%s-results.csv"' % (activity.slug,)

    writer = csv.writer(response)
    header = ['Name', 'Emplid', 'Username', 'Last Submission']
    if multiple_versions:
        q_headers = [('Version #%i' % (i+1,), 'Answer #%i' % (i+1,)) for i,_ in enumerate(questions)]
        header.extend(itertools.chain.from_iterable(q_headers))
    else:
        q_headers = ['Answer #%i' % (i+1,) for i,_ in enumerate(questions)]
        header.extend(q_headers)
    writer.writerow(header)

    for m, answers in by_student:
        answers = list(answers)
        answers_lookup = {a.question_id: a for a in answers}
        lastmod = max(a.modified_at for a in answers)

        row = [m.person.sortname_pref(), m.person.emplid, m.person.userid, lastmod]

        for q in questions:
            if q.id in answers_lookup:
                v = version_number_lookup[q.id].get(answers_lookup[q.id].question_version_id, 0)
                a = answers_lookup[q.id].question_version.helper(question=q).to_text(answers_lookup[q.id])
            else:
                v = None
                a = None

            if multiple_versions:
                row.append(v)
            row.append(a)

        writer.writerow(row)

    return response