Example #1
0
def submit(request):
    if request.method == "POST":
        form = SubmissionForm(request.POST)
        if form.is_valid():
            caption = form.cleaned_data['caption']
            url = form.cleaned_data['image_url']
            categories = [category.pk for category in Category.objects.all()]

            im = Image(caption=caption, url=url, user=request.user)
            try:
                im.save(
                )  # need to save before adding many to many relationships
            except IntegrityError:
                # assume url column not unique..image already added
                im = Image.objects.get(url=url)
                return redirect('/im/%d' % im.pk)
            im.apply_categories(categories)

            messages.success(request, 'Image submitted successfully!')
            return redirect('/submit')
    else:
        form = SubmissionForm()

    return render_to_response("submit.html", {
        'form': form,
    },
                              context_instance=RequestContext(request))
Example #2
0
def submit(request):
    if request.method == "POST":
        form = SubmissionForm(request.POST)
        if form.is_valid():
            caption = form.cleaned_data['caption']
            url = form.cleaned_data['image_url']
            categories = [category.pk for category in Category.objects.all()]
            
            im = Image(caption=caption, 
                       url=url,
                       user=request.user)
            try:
                im.save() # need to save before adding many to many relationships
            except IntegrityError:
                # assume url column not unique..image already added
                im = Image.objects.get(url=url)
                return redirect('/im/%d' % im.pk)
            im.apply_categories(categories)
            
            messages.success(request, 'Image submitted successfully!')
            return redirect('/submit')
    else:
        form = SubmissionForm()
    
    return render_to_response("submit.html", {
            'form': form,
        },
        context_instance = RequestContext(request)
    )
Example #3
0
def homework(request, pk):
    context = {}
    hwk = BookNode.objects.get(pk=pk)
    context['module'] = hwk.get_book().module
    context['homework'] = hwk
    # context['subtree'] = ex.get_descendants(include_self=True)
    chapter = hwk.get_parent_chapter()
    context['chapter'] = chapter
    context['book'] = hwk.get_book()
    homeworks = chapter.get_descendants().filter(node_type="homework").order_by('mpath')
    context["toc"] = homeworks

    # navigation
    next = homeworks.filter( mpath__gt=hwk.mpath )
    prev = homeworks.filter( mpath__lt=hwk.mpath ).order_by('-mpath')
    context['nnext'] = next[0] if next else None
    context['prev'] = prev[0] if prev else None

    questions = BookNode.objects.filter(node_type='question', mpath__startswith=hwk.mpath).order_by('mpath')
    context['questions'] = questions
    answers = []

    # create question-answer pairs (answer=None is not yet attempted/saved)
    for qu in questions:
        answers.append( Answer.objects.filter(user=request.user, question=qu).first() )
    context['answers'] = answers
    pairs = zip(questions,answers)
    context['pairs'] = pairs

    # check whether this homework has already been submitted
    sub = Submission.objects.filter(user=request.user, assignment=hwk).first()
    if sub:
        context['submission'] = sub

    # submit form: hitch on hidden fields here
    form = SubmissionForm( initial={'user': request.user, 'assignment':hwk.pk, 'declaraion': False} )
    form.fields['answers'] = answers
    context['form'] = form

    if request.method == 'POST':
        # deal with form (submit)
        form = SubmissionForm(request.POST)
        if form.is_valid():
            print form.cleaned_data
            if 'submit-homework' in request.POST:
                submission = form.save(commit=False)
                submission.save()
                # for answer in form.cleaned_data['answers']:
                for answer in answers:
                    if answer:
                        answer.submission = submission
                        answer.is_readonly = True
                        answer.save()
            return HttpResponseRedirect( reverse('homework', kwargs={'pk': hwk.id}) )
        else:
            context['debug'] = form.errors
            return render_to_response('index.html', context)
    else: # not POST
        return render_to_response('homework.html', context)
Example #4
0
def test_create(challenge, user):
    assert challenge.is_active()
    submission_form = SubmissionForm()
    assert not submission_form.is_valid()
    container_form = ContainerForm()
    assert not container_form.is_valid()

    container_form = ContainerForm(
        data={
            "container-name": "My Container",
            "container-challenge": challenge,
            "container-registry": "docker",
            "container-label": "foo",
        })
    assert container_form.is_valid()
    container = container_form.save(commit=False)
    container.user = user
    container.save()
    submission_form = SubmissionForm(data={
        "submission-name": "Test submission",
    })
    print(submission_form.errors)
    assert submission_form.is_valid()

    submission = submission_form.save(commit=False)
    submission.user = user
    submission.container = container
    submission.challenge = container.challenge
    submission.save()
    assert submission.draft_mode
Example #5
0
 def get_context_data(self, **kwargs):
     context = super(DetailContestProblemView, self)\
         .get_context_data(**kwargs)
     submission_form = SubmissionForm()
     context['submission_form'] = submission_form
     contest_pk = self.kwargs['contest_pk']
     contest = get_object_or_404(Contest, pk=contest_pk)
     if timezone.now() <= contest.end_datetime:
         context['is_contest_submission'] = True
     else:
         context['is_contest_submission'] = False
     context['contest'] = contest
     return context
Example #6
0
def test_update_submission(client, user, draft_submission):
    client.force_login(user)
    submission_form = SubmissionForm(instance=draft_submission)
    container_form = ContainerForm(instance=draft_submission.container)

    def skey(key):
        return f"{submission_form.prefix}-{key}"

    def ckey(key):
        return f"{container_form.prefix}-{key}"

    form_data = {
        skey(key): "sample data"
        for key, field in submission_form.fields.items()
        if isinstance(field, CharField)
    }
    form_data[skey("url")] = "http://test.org"
    form_data[skey("draft_mode")] = False
    form_data[skey("category")] = "Mixed"
    form_data[skey("ranked")] = False
    form_data.update({
        skey(key): value
        for key, value in submission_form.initial.items() if value
    })
    form_data.update({"args-TOTAL_FORMS": 0, "args-INITIAL_FORMS": 0})
    response = client.post(f"/submission/{draft_submission.pk}/edit/",
                           form_data)
    assert response.status_code == 200
    assert response.context["submission_form"].is_valid()
    assert not response.context["container_form"].is_valid()
    form_data.update({
        ckey(key): value
        for key, value in container_form.initial.items() if value
    })
    response = client.post(f"/submission/{draft_submission.pk}/edit/",
                           form_data)
    assert response.status_code == 302
    assert response.url == reverse("submission-detail",
                                   kwargs={"pk": draft_submission.pk})
    response = client.get(response.url)
    submission = response.context["submission"]
    assert submission.draft_mode
Example #7
0
def sctest(request, pk):
    context = {}
    test = BookNode.objects.get(pk=pk)
    chapter = test.get_parent_chapter()
    questions = BookNode.objects.filter(node_type='question', mpath__startswith=test.mpath).order_by('mpath')

    context['module'] = chapter.get_book().module
    context['test'] = test
    context['chapter'] = chapter
    context['questions'] = questions
    context['book']  = chapter.get_book()
    context['toc'] = BookNode.objects.filter( node_type="homework", mpath__startswith=chapter.mpath ).order_by('mpath')

    # navigation
    tests = BookNode.objects.filter( node_type__in=['singlechoice','multiplechoice'], mpath__startswith=chapter.mpath ).order_by('mpath')
    next = tests.filter( mpath__gt=test.mpath )
    prev = tests.filter( mpath__lt=test.mpath ).order_by('-mpath')
    context['next'] = next[0] if next else None
    context['prev'] = prev[0] if prev else None

    triplets = []

    # create question-choices-answer triplets (answer=None is not yet attempted)
    for qu in questions:
        choices = BookNode.objects.filter( node_type__in=['choice','correctchoice'], mpath__startswith=qu.mpath)
        answer = SingleChoiceAnswer.objects.filter(user=request.user, question=qu).first() # returns none if not yet attempted
        triplets.append([ qu, choices, answer])

    context['triplets'] = triplets

    # check whether this homework has already been attempted
    submission = Submission.objects.filter(user=request.user, assignment=test).first()
    if submission:
        context['submission'] = submission

    # form: hitch on hidden fields here
    form = SubmissionForm( initial={'user': request.user, 'assignment':test.pk} )
    context['form'] = form

    if request.method == 'POST':
        # deal with form (submit)
        # print request.POST
        form = SubmissionForm(request.POST)
        if form.is_valid():

            # extract chosen answers through raw post data (oops!)
            pairs = dict([ [int(k.split('_')[1]),int(v.split('_')[1])] for k,v in form.data.items() if k[:9] == 'question_'])
            for trip in triplets:
                qu = trip[0]
                ch = trip[1]
                an = trip[2]
                if qu.number in pairs:
                    chno = pairs[qu.number]
                    cho = ch[chno-1]
                    if an:
                        an.delete()
                    an = SingleChoiceAnswer(user=request.user, question=qu, choice=cho)
                    an.save
                    trip[2] = an

            context["triplets"] = triplets
            form = SubmissionForm( initial={'user': request.user, 'assignment':test.pk} )
            context['form'] = form

            if 'submit-test' in request.POST:

                # update submission
                submission = form.save(commit=False)
                submission.save()
                # we need to update the answers too
                for answer in form.cleaned_data['answers']:
                    if answer:
                        answer.submission = submission
                        answer.save()
            return render_to_response('sctest.html', context)

        else:
            context['debug'] = form.errors
            return render_to_response('index.html', context)
    else: # not POST
        return render_to_response('sctest.html', context)
Example #8
0
def homework(request, pk):
    context = {}
    hwk = BookNode.objects.get(pk=pk)
    context['module'] = hwk.get_book().module
    context['homework'] = hwk
    # context['subtree'] = ex.get_descendants(include_self=True)
    chapter = hwk.get_parent_chapter()
    context['chapter'] = chapter
    context['book'] = hwk.get_book()
    homeworks = chapter.get_descendants().filter(
        node_type="homework").order_by('mpath')
    context["toc"] = homeworks

    # navigation
    next = homeworks.filter(mpath__gt=hwk.mpath)
    prev = homeworks.filter(mpath__lt=hwk.mpath).order_by('-mpath')
    context['nnext'] = next[0] if next else None
    context['prev'] = prev[0] if prev else None

    questions = BookNode.objects.filter(
        node_type='question', mpath__startswith=hwk.mpath).order_by('mpath')
    context['questions'] = questions
    answers = []

    # create question-answer pairs (answer=None is not yet attempted/saved)
    for qu in questions:
        answers.append(
            Answer.objects.filter(user=request.user, question=qu).first())
    context['answers'] = answers
    pairs = zip(questions, answers)
    context['pairs'] = pairs

    # check whether this homework has already been submitted
    sub = Submission.objects.filter(user=request.user, assignment=hwk).first()
    if sub:
        context['submission'] = sub

    # submit form: hitch on hidden fields here
    form = SubmissionForm(initial={
        'user': request.user,
        'assignment': hwk.pk,
        'declaraion': False
    })
    form.fields['answers'] = answers
    context['form'] = form

    if request.method == 'POST':
        # deal with form (submit)
        form = SubmissionForm(request.POST)
        if form.is_valid():
            print form.cleaned_data
            if 'submit-homework' in request.POST:
                submission = form.save(commit=False)
                submission.save()
                # for answer in form.cleaned_data['answers']:
                for answer in answers:
                    if answer:
                        answer.submission = submission
                        answer.is_readonly = True
                        answer.save()
            return HttpResponseRedirect(
                reverse('homework', kwargs={'pk': hwk.id}))
        else:
            context['debug'] = form.errors
            return render_to_response('index.html', context)
    else:  # not POST
        return render_to_response('homework.html', context)
Example #9
0
def sctest(request, pk):
    context = {}
    test = BookNode.objects.get(pk=pk)
    chapter = test.get_parent_chapter()
    questions = BookNode.objects.filter(
        node_type='question', mpath__startswith=test.mpath).order_by('mpath')

    context['module'] = chapter.get_book().module
    context['test'] = test
    context['chapter'] = chapter
    context['questions'] = questions
    context['book'] = chapter.get_book()
    context['toc'] = BookNode.objects.filter(
        node_type="homework",
        mpath__startswith=chapter.mpath).order_by('mpath')

    # navigation
    tests = BookNode.objects.filter(
        node_type__in=['singlechoice', 'multiplechoice'],
        mpath__startswith=chapter.mpath).order_by('mpath')
    next = tests.filter(mpath__gt=test.mpath)
    prev = tests.filter(mpath__lt=test.mpath).order_by('-mpath')
    context['next'] = next[0] if next else None
    context['prev'] = prev[0] if prev else None

    triplets = []

    # create question-choices-answer triplets (answer=None is not yet attempted)
    for qu in questions:
        choices = BookNode.objects.filter(
            node_type__in=['choice', 'correctchoice'],
            mpath__startswith=qu.mpath)
        answer = SingleChoiceAnswer.objects.filter(
            user=request.user,
            question=qu).first()  # returns none if not yet attempted
        triplets.append([qu, choices, answer])

    context['triplets'] = triplets

    # check whether this homework has already been attempted
    submission = Submission.objects.filter(user=request.user,
                                           assignment=test).first()
    if submission:
        context['submission'] = submission

    # form: hitch on hidden fields here
    form = SubmissionForm(initial={
        'user': request.user,
        'assignment': test.pk
    })
    context['form'] = form

    if request.method == 'POST':
        # deal with form (submit)
        # print request.POST
        form = SubmissionForm(request.POST)
        if form.is_valid():

            # extract chosen answers through raw post data (oops!)
            pairs = dict([[int(k.split('_')[1]),
                           int(v.split('_')[1])] for k, v in form.data.items()
                          if k[:9] == 'question_'])
            for trip in triplets:
                qu = trip[0]
                ch = trip[1]
                an = trip[2]
                if qu.number in pairs:
                    chno = pairs[qu.number]
                    cho = ch[chno - 1]
                    if an:
                        an.delete()
                    an = SingleChoiceAnswer(user=request.user,
                                            question=qu,
                                            choice=cho)
                    an.save
                    trip[2] = an

            context["triplets"] = triplets
            form = SubmissionForm(initial={
                'user': request.user,
                'assignment': test.pk
            })
            context['form'] = form

            if 'submit-test' in request.POST:

                # update submission
                submission = form.save(commit=False)
                submission.save()
                # we need to update the answers too
                for answer in form.cleaned_data['answers']:
                    if answer:
                        answer.submission = submission
                        answer.save()
            return render_to_response('sctest.html', context)

        else:
            context['debug'] = form.errors
            return render_to_response('index.html', context)
    else:  # not POST
        return render_to_response('sctest.html', context)
 def get_context_data(self, **kwargs):
     context = super(DetailProblemView, self).get_context_data(**kwargs)
     submission_form = SubmissionForm()
     context['submission_form'] = submission_form
     return context