コード例 #1
0
ファイル: views.py プロジェクト: kartikshah1/Test
def upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Upload(filePath = request.FILES['docfile'])
            newdoc.owner = request.user

            #Overwrite file if already exist.
            '''documents = Upload.objects.filter(owner=request.user)
            if documents:
                #print os.path.join(MEDIA_ROOT, documents[0].filePath.name)
                os.remove(os.path.join(MEDIA_ROOT, documents[0].filePath.name))
                documents.delete()'''
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('upload.views.upload'))
    else:
        form = UploadForm()

    documents = Upload.objects.filter(owner=request.user)
    return render_to_response(
                'upload/upload.html',
                {'form':form, 'documents': documents},
                context_instance=RequestContext(request)
            )
コード例 #2
0
def upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Upload(filePath=request.FILES['docfile'])
            newdoc.owner = request.user

            #Overwrite file if already exist.
            '''documents = Upload.objects.filter(owner=request.user)
            if documents:
                #print os.path.join(MEDIA_ROOT, documents[0].filePath.name)
                os.remove(os.path.join(MEDIA_ROOT, documents[0].filePath.name))
                documents.delete()'''
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('upload.views.upload'))
    else:
        form = UploadForm()

    documents = Upload.objects.filter(owner=request.user)
    return render_to_response('upload/upload.html', {
        'form': form,
        'documents': documents
    },
                              context_instance=RequestContext(request))
コード例 #3
0
ファイル: views.py プロジェクト: adieu/upload-sample
def upload_handler(request):
    view_url = reverse('upload.views.upload_handler')
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect(view_url)

    upload_url, upload_data = prepare_upload(request, view_url)
    form = UploadForm()
    return direct_to_template(request, 'upload/upload.html',
        {'form': form, 'upload_url': upload_url, 'upload_data': upload_data,
         'uploads': UploadModel.objects.all()})
コード例 #4
0
def uploadAssignment(request, assignmentID):
    if request.method == 'POST':
        assignment = get_object_or_404(Assignment, pk=assignmentID)
        form = UploadForm(request.POST,
                          request.FILES,
                          assignment_model_obj=assignment)
        if form.is_valid():
            newUpload = Upload(owner=request.user,
                               assignment=assignment,
                               filePath=request.FILES['docfile'])
            newUpload.save()
        else:
            return form.errors
コード例 #5
0
ファイル: views.py プロジェクト: kartikshah1/Test
def uploadAssignment(request, assignmentID):
    if request.method == 'POST':
        assignment = get_object_or_404(Assignment, pk=assignmentID)
        form = UploadForm(request.POST, request.FILES, assignment_model_obj=assignment)
        if form.is_valid():
            newUpload = Upload(
                               owner = request.user,
                               assignment = assignment,
                               filePath = request.FILES['docfile']
                            )
            newUpload.save()
        else:
            return form.errors
コード例 #6
0
def delete_data(request, pk):
    data = get_object_or_404(UploadedFile, pk=pk)
    print('in delete / data: ', data)
    if request.method == 'POST':
        form = UploadForm(request.POST, instance=data)
    else:
        form = UploadForm(instance=data)
    return HomeView.get(request)

    for file in UploadedFile.objects.all():
        file.file.delete()
        file.delete()
    return redirect(request.POST.get('next'))
コード例 #7
0
def upload_view(request):
    """Renders the /uploads/ page.

    Parameters
    ----------
    request : `django.requst.HttpRequest`
        HTTP request made to the server.
    """
    if request.method == 'GET':
        form = UploadForm()
    else:
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            return JsonResponse({
                'action': 'replace',
                'html': form.form_valid(request),
            })
        else:
            return JsonResponse({
                'action': 'replace',
                'html': form.as_html(request),
            })

    return render(request, 'upload.html', {
        'form': form,
        'form_as_html': form.as_html(request),
    })
コード例 #8
0
ファイル: views.py プロジェクト: serkanh/Yupeat
def upload_handler(request):
    view_url = reverse('upload.views.upload_handler')
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        try:
            if form.is_valid():
                form.save()
            else:
                view_url += '?error=Not a valid image'
            return HttpResponseRedirect(view_url)
        except Exception,e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error('caught %s in image upload',e)
            raise e
コード例 #9
0
ファイル: views.py プロジェクト: big-jump/dumponus
def upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            upload = form.save(commit=False)
            upload.ip = request.META.get('REMOTE_ADDR', '0.0.0.0')
            upload.save()
            messages.success(request, "Upload was successful!")
            return HttpResponseRedirect(reverse('upload-detail', args=[upload.id]))
    else:
        form = UploadForm()

    return render_to_response('upload/index.html', {
        'form': form,  
        'latest': Upload.objects.order_by('-created')[:20],
    }, context_instance=RequestContext(request))
コード例 #10
0
ファイル: views.py プロジェクト: xiezq1989/efiles_system
def file_upload(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            username = request.user.username
            filename=form.cleaned_data['file_url']
            file_url=form.cleaned_data['file_url']
            #pdb.set_trace()
            efile_upload=Upload()
            efile_upload.user_name=username
            efile_upload.title_name = filename
            efile_upload.file_url = file_url
            efile_upload.file_size=request.FILES['file_url'].size # Get the size of uploaded file from file's object
            efile_upload.save()
        #return HttpResponse(str(filename)+' had uploaded Success')
            messages.success(request,'上传成功')
    else:
        form = UploadForm()
    return render(request, 'upload/upload.html', {'form': form})
コード例 #11
0
ファイル: views.py プロジェクト: JoshuaOluoch/Upload-File
def list_file(request):
    # file upload view
    if request.method == "POST":
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            newfile = Upload(upload_file=request.FILES["upload_file"], username=request.user.username)
            newfile.save()

            # Redirect to the file list after POST
            return HttpResponseRedirect("")
    else:
        form = UploadForm()  # A empty, unbound form

    # Load documents for the list page
    files = Upload.objects.all().filter(username=request.user.username)

    # Render list page with the documents and the form
    return render_to_response(
        "upload/list_file.html", {"files": files, "form": form}, context_instance=RequestContext(request)
    )
コード例 #12
0
def upload_new(request):
    if request.method == "POST":
        form = UploadForm(request.POST, request.FILES)
        filename = request.FILES['projectFile'].name
        print(filename)

        if form.is_valid():
            post = form.save(commit=False)
            #post.email = request.user
            post.save()

            f = open(settings.MEDIA_ROOT + '/files/' + filename,
                     'r',
                     encoding='utf8')
            result = SnRdata(f)
            print("=============json=============")
            '''
            for i in range(len(result)):
                print("DATA_"+str(i))
                print(result)
                '''
            print(result)
            print("=============json=============")
            f.close()
        '''
            #if(request.contentType == 'text/html'
            #return redirect('upload_base', pk=post.pk)
            #return "{success: 'ok'}"
        '''
    else:
        form = UploadForm()
    return render(request, 'upload_new.html', {'form': form})
コード例 #13
0
def list_file(request):
    # file upload view
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            newfile = Upload(upload_file = request.FILES['upload_file'],username=request.user.username)
            newfile.save()

            # Redirect to the file list after POST
            return HttpResponseRedirect('')
    else:
        form = UploadForm() # A empty, unbound form

    # Load documents for the list page
    files = Upload.objects.all().filter(username = request.user.username)

    # Render list page with the documents and the form
    return render_to_response(
        'upload/list_file.html',
        {'files': files, 'form': form},
        context_instance=RequestContext(request)
    )
コード例 #14
0
    def test_0_form_workflow_add_manually(self):
        # test just the form
        # create auxiliary json file
        jsonFileName = "/tmp/workflow.json"
        f = open(jsonFileName, "w")
        f.write(self.populate.getJson())
        f.close()
        upload_file = open(jsonFileName, "rb")
        file_dict = {
            NAME_JSON: SimpleUploadedFile(upload_file.name, upload_file.read())
        }

        # get category IDs for the select Category field
        categories = Category.objects.all()
        category0 = categories[0]
        category1 = categories[1]
        #category0 = Category.objects.get(name=self.data[CATEGORY][0])
        #category1 = Category.objects.get(name=self.data[CATEGORY][1])
        # new workflow name
        workFlowName = 'workflow999'
        data_dict = {
            NAME_NAME: workFlowName,
            NAME_CATEGORY: [category0.id, category1.id],
            NAME_KEYWORDS: self.populate.getParragraph(1, 14),
            NAME_DESCRIPTION: self.populate.getParragraph(23, 123),
            NAME_VERSION: '3.1415',
        }

        # form with fieldfields has two independent dictionaries
        form = WorkFlowFormBase(data=data_dict, files=file_dict)
        self.assertTrue(form.is_valid(), form.errors)
        if form.is_valid():
            file_data = form.cleaned_data["json"].read().decode("utf-8")
            # modify object json value
            form.instance.json = file_data
        newWorkflow = form.save()
        self.assertEqual(newWorkflow.name, workFlowName)
コード例 #15
0
def index(request):
    if request.method == 'POST':
        print("-- post --")
        form = UploadForm(request.POST or None)
        if form.is_valid():
            print("valid")
            image_file = ImageFileModel()
            image_file.image = request.FILES['image']
            image_file.published_date = timezone.now()

            image_file.save()
            form.save()
            render(request, 'upload/index.html', {'form': form})
        else:
            print("not")
            form = UploadForm()
            render(request, 'upload/index.html', {'form': form})
    else:
        form = UploadForm()
    return render(request, 'upload/index.html', {'form': form})
コード例 #16
0
 def post(self, request):
     if not request.user.is_superuser:
         try:
             author = request.user.groups.get(name='author')
             logger.info("Author: {}".format(author))
         except Exception as e:
             logger.error(e)
             raise Http404('Not found')
     try:
         file = request.FILES['file']
         fs = FileSystemStorage()
         new_filename = file.name.replace(" ", "_")
         filename = fs.save(
             os.path.join(BASE_DIR, 'uploads/%s' % new_filename), file)
         logger.info('filename: ', filename)
         upload_file_url = '/' + fs.url(filename)
         idx = upload_file_url.rindex('/') + 1
         path_file = upload_file_url[idx:len(upload_file_url)]
         posts = []
         with open(upload_file_url, 'r', newline='',
                   encoding='utf-8') as csvFile:
             reader = csv.reader(csvFile, quoting=csv.QUOTE_MINIMAL)
             next(reader)
             for row in reader:
                 post = dict(name=row[0],
                             thumbnail=row[1],
                             new=row[2],
                             min_range=row[3],
                             max_range=row[4],
                             content=row[5],
                             content_activity=row[6],
                             preview=row[7],
                             tags=row[8])
                 posts.append(post)
             print(posts)
         csvFile.close()
     except Exception as e:
         return JsonResponse(dict(error="%s" % e))
     upload_form = UploadForm()
     return render(
         request, self.template_name,
         dict(posts=posts,
              file=path_file,
              length=len(posts),
              form=upload_form))
コード例 #17
0
ファイル: views.py プロジェクト: kartikshah1/Test
def detailsAssignment(request, assignmentID):
    assignment = get_object_or_404(Assignment, pk=assignmentID)
    course = assignment.course
    course_history = CourseHistory.objects.get(course_id=course,
                                               user_id=request.user.id)
    course_info = CourseInfo.objects.get(pk=course.course_info_id)
    is_creator = isCourseCreator(course, request.user)
    is_moderator = isCourseModerator(course, request.user)

    has_joined = CourseHistory.objects.filter(course_id=course,
                                              user_id=request.user.id)
    if assignment.late_submission_allowed:
        submission_allowed = (timezone.now() <=
                              assignment.hard_deadline) and bool(has_joined)
    else:
        submission_allowed = (timezone.now() <=
                              assignment.deadline) and bool(has_joined)

    is_due = (timezone.now() >= assignment.deadline)  # and bool(has_joined)

    if request.method == "POST" and submission_allowed:
        form = UploadForm(request.POST,
                          request.FILES,
                          assignment_model_obj=assignment)
        if form.is_valid():
            older_upload = Upload.objects.filter(owner=request.user,
                                                 assignment=assignment)
            if older_upload:
                older_upload[0].delete()
            newUpload = Upload(owner=request.user,
                               assignment=assignment,
                               filePath=request.FILES['docfile'])
            newUpload.save()
            return HttpResponseRedirect(
                reverse('assignments_details',
                        kwargs={'assignmentID': assignmentID}))
    else:
        form = UploadForm()

    perror_ctype = ContentType.objects.get_for_model(ProgramErrors)
    terror_ctype = ContentType.objects.get_for_model(TestcaseErrors)
    program_errors = []
    test_errors = []

    for error in AssignmentErrors.objects.filter(assignment=assignment,
                                                 content_type=terror_ctype):
        test_errors.extend(TestcaseErrors.objects.filter(pk=error.object_id))

    for error in AssignmentErrors.objects.filter(assignment=assignment,
                                                 content_type=perror_ctype):
        program_errors.extend(ProgramErrors.objects.filter(pk=error.object_id))

    course = assignment.course
    programs = Program.objects.filter(assignment=assignment)
    #test_cases = Testcase.objects.filter(program__in=programs)

    practice_program = [
        a_program for a_program in programs
        if a_program.program_type == "Practice"
    ]
    programs_with_errors = []

    for aprogram in programs:
        if not aprogram.is_sane:
            try:
                p_error = ProgramErrors.objects.get(program=aprogram)
                programs_with_errors.append(p_error)
            except ProgramErrors.DoesNotExist:
                p_error = None

    submittedFiles = Upload.objects.filter(owner=request.user,
                                           assignment=assignment)

    program_not_ready = False
    disable_grading = False
    if programs_with_errors or submission_allowed == False:
        program_not_ready = True
    if (submittedFiles and submittedFiles[0].is_stale):
        disable_grading = True

    all_assignments = Assignment.objects.filter(
        course=course).order_by('-serial_number')
    if request.user == assignment.creater:
        assignments = all_assignments
    else:
        assignments = [
            a for a in all_assignments if a.publish_on <= timezone.now()
        ]

    total_sumissions = Upload.objects.filter(assignment=assignment).count()
    isSubmitted = Upload.objects.filter(assignment=assignment).count() > 0
    get_params = {'source': 'assignment', 'id': assignmentID}

    return render_to_response(
        'assignments/details.html',
        {
            'assignment': assignment,
            'course': course,
            'has_joined': has_joined,
            'is_moderator': is_moderator,
            'programs': programs,
            'form': form,
            'submission_allowed': submission_allowed,
            'submittedFiles': submittedFiles,
            'programs_with_errors': programs_with_errors,
            'disable_grading': disable_grading,
            'program_not_ready': program_not_ready,
            'practice_program': practice_program,
            'assignments': assignments,
            'program_errors': program_errors,
            'test_errors': test_errors,
            'published': assignment.publish_on <= timezone.now(),
            'is_due': is_due,
            'isSubmitted': isSubmitted,
            'date_time': timezone.now(),
            'get_params': get_params,
            'total_sumissions': total_sumissions
        },
        context_instance=RequestContext(request),
    )
コード例 #18
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data()
     context['form'] = UploadForm()
     return context
コード例 #19
0
ファイル: views.py プロジェクト: kartikshah1/Test
def detailsAssignment(request, assignmentID):
    assignment = get_object_or_404(Assignment, pk=assignmentID)
    course = assignment.course
    course_history = CourseHistory.objects.get(course_id=course, user_id=request.user.id)
    course_info = CourseInfo.objects.get(pk=course.course_info_id)
    is_creator = isCourseCreator(course, request.user)
    is_moderator = isCourseModerator(course, request.user)

    has_joined = CourseHistory.objects.filter(course_id=course, user_id=request.user.id)
    if assignment.late_submission_allowed:
        submission_allowed = (timezone.now() <= assignment.hard_deadline) and bool(has_joined)
    else:
        submission_allowed = (timezone.now() <= assignment.deadline) and bool(has_joined)

    is_due = (timezone.now() >= assignment.deadline)# and bool(has_joined)

    if request.method == "POST" and submission_allowed:
        form = UploadForm(request.POST, request.FILES, assignment_model_obj=assignment)
        if form.is_valid():
            older_upload = Upload.objects.filter(
                                owner=request.user,
                                assignment=assignment
                            )
            if older_upload:
                older_upload[0].delete()
            newUpload = Upload(
                            owner=request.user,
                            assignment=assignment,
                            filePath=request.FILES['docfile']
                        )
            newUpload.save()
            return HttpResponseRedirect(reverse('assignments_details', kwargs={'assignmentID':assignmentID}))
    else:
        form = UploadForm()

    perror_ctype = ContentType.objects.get_for_model(ProgramErrors)
    terror_ctype = ContentType.objects.get_for_model(TestcaseErrors)
    program_errors = []
    test_errors = []

    for error in AssignmentErrors.objects.filter(assignment=assignment, content_type=terror_ctype):
        test_errors.extend(TestcaseErrors.objects.filter(pk=error.object_id))

    for error in AssignmentErrors.objects.filter(assignment=assignment, content_type=perror_ctype):
        program_errors.extend(ProgramErrors.objects.filter(pk=error.object_id))


    course = assignment.course
    programs = Program.objects.filter(assignment=assignment)
    #test_cases = Testcase.objects.filter(program__in=programs)

    practice_program = [a_program for a_program in programs if a_program.program_type == "Practice"]
    programs_with_errors = []

    for aprogram in programs:
        if not aprogram.is_sane:
            try:
                p_error = ProgramErrors.objects.get(program=aprogram)
                programs_with_errors.append(p_error)
            except ProgramErrors.DoesNotExist:
                p_error = None

    submittedFiles = Upload.objects.filter(owner=request.user, assignment=assignment)
    
    program_not_ready = False
    disable_grading = False
    if programs_with_errors or submission_allowed == False:
    	program_not_ready = True
    if (submittedFiles and submittedFiles[0].is_stale) :
        disable_grading = True

    all_assignments = Assignment.objects.filter(course=course).order_by('-serial_number')
    if request.user == assignment.creater:
        assignments = all_assignments
    else:
        assignments = [a for a in all_assignments if a.publish_on <= timezone.now()]

    total_sumissions = Upload.objects.filter(assignment=assignment).count()
    isSubmitted = Upload.objects.filter(assignment=assignment).count() > 0
    get_params = {'source': 'assignment', 'id': assignmentID}

    return render_to_response(
                'assignments/details.html',
                {'assignment': assignment, 'course': course, 'has_joined': has_joined, 'is_moderator':is_moderator,
                'programs': programs, 'form': form, 'submission_allowed': submission_allowed,
                'submittedFiles': submittedFiles, 'programs_with_errors': programs_with_errors,
                'disable_grading': disable_grading, 'program_not_ready':program_not_ready, 'practice_program': practice_program,
                'assignments' : assignments, 'program_errors':program_errors, 'test_errors':test_errors,
                'published': assignment.publish_on <= timezone.now(), 'is_due': is_due,
                'isSubmitted':isSubmitted, 'date_time': timezone.now(), 'get_params': get_params,
                'total_sumissions': total_sumissions},
                context_instance=RequestContext(request),
            )