Exemple #1
0
def pp_imgsource_form(context, nodelist, *args, **kwargs):
	'''
	This block tag can create or process forms eitfrom genericview.views import HttpRedirectException, namespace_gether to create or to modify arguments.
	Usage is as follows:

	{% pp_topic_form POST=request.POST path=request.path topic=pp_topic.topic root=some_topic %}
	   Do stuff with {{ pp_source.form }}.
	{% endpp_topic_form %}
	'''
	context.push()
	namespace = get_namespace(context)

	POST = kwargs.get('POST', None)
	FILE = kwargs.get('FILE', None)
	obj = kwargs.get('object', None)
	request = kwargs.get('request', None)

	content_type = ContentType.objects.get_for_model(obj)

	view_url = reverse('pirate_sources.views.upload_handler', args=[obj.pk, content_type.pk])
	if POST:
		form = IMGSourceForm(POST, FILE)
		if form.is_valid():
			img = form.save()
			img.user = request.user
			img.object_pk = obj.pk
			img.content_type = ContentType.objects.get(pk=content_type.pk)
			img.submit_date = datetime.datetime.now()

			img.make(request.FILES['file'], img.file.name)
			if img.private != True:
				try:
					oldimg = IMGSource.objects.get(object_pk=obj.pk, current=True)
					oldimg.current = False
					oldimg.save()
				except:
					pass
				img.current = True
			img.save()
			upload_url, upload_data = prepare_upload(request, view_url)
			form = IMGSourceForm()
		else:
			view_url += '?error=Not a valid image'
		namespace['errors'] = form.errors

	upload_url, upload_data = prepare_upload(request, view_url)
	form = IMGSourceForm()

	namespace['upload_url'] = upload_url
	namespace['upload_data'] = upload_data
	namespace['form'] = form
	output = nodelist.render(context)
	context.pop()

	return output
Exemple #2
0
def pp_imgsource_form(context, nodelist, *args, **kwargs):
    '''
    This block tag can create or process forms eitfrom genericview.views import HttpRedirectException, namespace_gether to create or to modify arguments.
    Usage is as follows:

    {% pp_topic_form POST=request.POST path=request.path topic=pp_topic.topic root=some_topic %}
       Do stuff with {{ pp_source.form }}.
    {% endpp_topic_form %}
    '''
    context.push()
    namespace = get_namespace(context)

    POST = kwargs.get('POST', None)
    FILE = kwargs.get('FILE', None)
    obj = kwargs.get('object', None)
    request = kwargs.get('request', None)

    content_type = ContentType.objects.get_for_model(obj)

    view_url = reverse('pirate_sources.views.upload_handler', args=[obj.pk, content_type.pk])
    if POST:
        form = IMGSourceForm(POST, FILE)
        if form.is_valid():
            img = form.save()
            img.user = request.user
            img.object_pk = obj.pk
            img.content_type = ContentType.objects.get(pk=content_type.pk)
            img.submit_date = datetime.datetime.now()

            img.make(request.FILES['file'], img.file.name)
            if img.private != True:
                try:
                    oldimg = IMGSource.objects.get(object_pk=obj.pk, current=True)
                    oldimg.current = False
                    oldimg.save()
                except:
                    pass
                img.current = True
            img.save()
            upload_url, upload_data = prepare_upload(request, view_url)
            form = IMGSourceForm()
        else:
            view_url += '?error=Not a valid image'
        namespace['errors'] = form.errors

    upload_url, upload_data = prepare_upload(request, view_url)
    form = IMGSourceForm()

    namespace['upload_url'] = upload_url
    namespace['upload_data'] = upload_data
    namespace['form'] = form
    output = nodelist.render(context)
    context.pop()

    return output
def upload_handler(request, lat, lon):
    assert(request.method == 'POST')
    form = UploadForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
    return HttpResponseRedirect("/home")
    upload_url, upload_data = prepare_upload(request, "/upload/")
    form = UploadForm()
    return render(request, 'upload.html',
        {'form': form, 'upload_url': upload_url, 'upload_data': upload_data,
         'uploads': FileUpload.objects.all()})

    upload_url, upload_data = prepare_upload(request, view_url)
def detail(request, slug):
    inst = get_object_or_404(Institution, slug__exact=slug)

    msg_form = MessageForm(inst)
    upload_url, upload_data = prepare_upload(request, reverse('portal.messages.views.attach_file'))

    ctx = {
        'request'    : request,
        'institution': inst,
        'photo_count': 0,
        'files'      : UploadedFile.objects.for_model(inst).all(),
        'next'       : reverse('portal.institutions.views.detail', args=[slug,]),
        'msg_form'   : msg_form,
        'attach_form': AttachmentForm(),
        'upload_url' : upload_url,
        'upload_data': upload_data,
    }

    albums = Album.objects.for_model(inst)
    if albums.exists():
        ctx['albums'] = albums.all()
        qtd = 0
        for album in albums:
            qtd += album.picture_album_set.count()
        ctx['photo_count'] = qtd

    return direct_to_template(request, 'institutions/detail.html', ctx)
def upload_handler(request):
    view_url = reverse('image_recognition.views.upload_handler')
    recognized = None
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            instance = UploadModel(file=request.FILES['file'])
            instance.save()
            return HttpResponseRedirect(view_url)

    files = UploadModel.objects.all()
    if files:
        last = UploadModel.objects.latest('file')
        file_path = settings.MEDIA_ROOT + last.file.name
        recognized = subprocess.check_output(["/usr/bin/gocr", file_path])

    files.delete()

    upload_url, upload_data = prepare_upload(request, view_url)
    form = UploadForm()
    return render_to_response(
            'image_recognition/upload.html',
            {'form': form, 'upload_url': upload_url,
             'upload_data': upload_data, 'recognized': recognized},
            context_instance=RequestContext(request)
    )
Exemple #6
0
def upload_handler(request):
    context = RequestContext(request)
    view_url = reverse('handle_requests.views.upload_handler')
    username = request.POST['username']
    password = request.POST['password']
    file_name = request.POST['file_name']
    size = request.POST['size']
    path = request.POST['path']
    user_id = check_auth(username, password, request)
    print "USER ID: " + str(user_id)
    if (user_id != -1):
        view_url = reverse('handle_requests.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()
        file_object = File(name=file_name,
                           path=path,
                           user_id=user_id,
                           size=size)
        file_object.save()
        mod = Modification(file_id=file_object.pk,
                           user_id=user_id,
                           mod_type='add')
        mod.save()
        return render(request, 'handle_requests/upload.html', {
            'form': form,
            'upload_url': upload_url,
            'upload_data': upload_data
        })
    else:
        return render(request, 'status.html', {'status': 'failure'})
def upload_handler(request,pk=None,entityID=None):
    view_url = reverse('google_dependency.blobstore_handler.upload_handler')
    absolute_url = '/resource/'

    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        entityID = request.POST['entityID']
        
        logger.debug('entityID: ' + entityID)
        param={}
        if form.is_valid():
            obj = form.save()
            
        return HttpResponseRedirect(absolute_url+str(obj.pk) + '/' + entityID)
    
    elif request.method == 'GET':
        upload_url, upload_data = prepare_upload(request, view_url)
        resource_url ={}
        thumbnail_url = {}
        if pk != None:
            resource_url= generate_resource_URL(request,pk,'440','0')
            thumbnail_url= generate_resource_URL(request,pk,'50','1')
        param={'upload_url': upload_url, 
               'upload_data': upload_data,
               'resource_url' : resource_url,
               'thumbnail_url' : thumbnail_url,
               'pk' : pk
             }
        #form = UploadForm()
        return direct_to_template(request, 'filetransferForm.html',param)
Exemple #8
0
def create_montage(request):

	if request.method == 'POST':
	    form = MontageCreateForm(request.POST, request.FILES)
	    print(dir(form))
	    if form.is_valid():
	    	print("hello")
	        montageElementContainer = MontageElementContainer(title = request.POST['title'])
	        montageElementContainer.save()

	        for file in request.FILES.getlist('files'):
	                montageElement = MontageElement(video_file=file, container=montageElementContainer)
	                montageElement.save()

	        # contextDict for data to be passed to next view
	        contextDict = {}
	        contextDict['title']                   = request.POST['title']
	        contextDict['montageElementContainer'] = montageElementContainer
	        contextDict['uid']                     = montageElementContainer.auto_increment_id

	        template = loader.get_template('montage_maker/builder.html')
	        context = RequestContext(request, contextDict)
	        return HttpResponse(template.render(context))

	else:
		#view_url = reverse('upload.views.upload_handler')
		upload_url, upload_data = prepare_upload(request, 'montage_maker/builder.html')
		form = MontageCreateForm()
	    # Render list page with the documents and the form
		return render_to_response(
	    	'montage_maker/create_montage.html',
	    	{'form': form, 'upload_url': upload_url, 'upload_data': upload_data},
	    	context_instance=RequestContext(request)
		)
Exemple #9
0
def create_new_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        form_profile = CreateProfileForm(request.POST, request.FILES)
        if form.is_valid() and form_profile.is_valid():
            user = form.save(commit=False)
            # user must be active for login to work
            user.is_active = True
            user.save()
            profile = form_profile.save(commit=False)
            profile.user = user #User.objects.get(username__exact=request.POST['username'])
            profile.save()
            return HttpResponseRedirect(reverse('django.contrib.auth.views.login'))
    else:
        form = UserCreationForm()
        form_profile = CreateProfileForm()
    view_url = reverse('fotos.views.create_new_user')
    upload_url, upload_data = prepare_upload(request, view_url)
    return render_to_response('user_create_form.html', 
                              context_instance=RequestContext(request,
                              {'request': request,
                               'form': form, 
                               'form_profile': form_profile,
                               'upload_url': upload_url,
                               'upload_data': upload_data}))
Exemple #10
0
def create_new_user(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        form_profile = CreateProfileForm(request.POST, request.FILES)
        if form.is_valid() and form_profile.is_valid():
            user = form.save(commit=False)
            # user must be active for login to work
            user.is_active = True
            user.save()
            profile = form_profile.save(commit=False)
            profile.user = user #User.objects.get(username__exact=request.POST['username'])
            profile.save()
            return HttpResponseRedirect(reverse('django.contrib.auth.views.login'))
    else:
        form = UserCreationForm()
        form_profile = CreateProfileForm()
    view_url = reverse('my.views.create_new_user')
    upload_url, upload_data = prepare_upload(request, view_url)
    return render_to_response('user_create_form.html', 
                              context_instance=RequestContext(request,
                              {'request': request,
                               'form': form, 
                               'form_profile': form_profile,
                               'upload_url': upload_url,
                               'upload_data': upload_data}))
Exemple #11
0
def upload_handler(request):
    context = RequestContext(request)
    view_url = reverse('handle_requests.views.upload_handler')
    username = request.POST['username']
    password = request.POST['password']
    file_name = request.POST['file_name']
    size = request.POST['size']
    path = request.POST['path']
    user_id = check_auth(username, password, request)
    print "USER ID: " + str(user_id)
    if(user_id!=-1):
        view_url = reverse('handle_requests.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()
        file_object = File(name=file_name, path = path, user_id = user_id, size=size )
        file_object.save()
        mod = Modification(file_id = file_object.pk, user_id = user_id, mod_type='add')
        mod.save()
        return render(request, 'handle_requests/upload.html',
                      {'form': form, 'upload_url': upload_url, 'upload_data': upload_data})
    else:
        return render(request, 'status.html', {'status': 'failure'})
Exemple #12
0
def file_upload(request):
    view_url = reverse(file_upload)

    if request.method == 'POST':
        form = File_upload(request.POST, request.FILES)
        if form.is_valid():
            cd = form.cleaned_data
            sf = Student_file(course = cd['course'],
                              owner = request.user,
                              note = cd['note'],
                              name = cd['name'],
                              file_type = cd['file_type'],
                              year = cd['year']
            )
            sf.save()
            return HttpResponseRedirect(reverse('engsci_conga.views.courses_view',
                                                kwargs = {'course': str(cd['course'])}
            ))
    else:
        form = File_upload

    upload_url, upload_data = prepare_upload(request, view_url)

    return render_to_response('upload_form.html', {'form': form, 'upload_url': upload_url, 'upload_data': upload_data},
                              context_instance = RequestContext(request))
Exemple #13
0
def scripts_page(request):
    is_valid = False
    is_post = False
    exp_id = 0
    view_url = '/robot_scripts_page/'
    upload_url, upload_data = prepare_upload(request, view_url)
    scriptstable = getScriptsTable(_user = request.user)
    if scriptstable.willHandle(request):
        return scriptstable.handleRequest(request)
    if request.method=='POST':
        is_post = True
        form = RobotScriptForm (request.POST, request.FILES) #bound form to project
        if form.is_valid():
            is_valid = True
            f=form.save(commit= False)
            f.user = request.user
            f.script_date = request.POST.get('date_0')
            f.script_time = request.POST.get('date_1')
            f=form.save(commit= True)
            script = RobotScript.objects.get(pk= f.id)
            #c = RequestContext(request,{'form':form,'messege':'New script submitted successfully','scriptstable':scriptstable ,'upload_url':upload_url,
             #                           'upload_data':upload_data,})
            #c.update(csrf(request))
        return HttpResponseRedirect(view_url)
    else:
        robotScript = RobotScript(user = request.user)
        form = RobotScriptForm(instance=robotScript)
        form.fields['user'].widget = django.forms.widgets.HiddenInput()
        return direct_to_template(request, 'scripts_page.html',
            { 'form':form,
              'is_valid':is_valid,
              'is_post':is_post,
              'upload_url':upload_url,
              'upload_data':upload_data,
              'scriptstable':scriptstable})
Exemple #14
0
def add_photo(request):
    if request.method == 'POST':
        form = AddPhotoForm(request.POST, request.FILES)
        if form.is_valid():
            photo = form.save(commit=False)
            blob_key = request.FILES['img'].blobstore_info._BlobInfo__key
            data = blobstore.BlobReader(blob_key).read()
            try:
                img = images.Image(image_data=data)
                photo.title = FromTranslit(form.data['title1'])
                photo.album = FromTranslit(form.data['album1'])
                photo.width = img.width
                photo.height = img.height
                photo.thumb_url = images.get_serving_url(blob_key)
                photo.author = request.user
                photo = form.save()            
                return HttpResponseRedirect(reverse('my.views.list_photos'))
            except:
                pass
    else:
        form = AddPhotoForm()
    view_url = reverse('my.views.add_photo')
    upload_url, upload_data = prepare_upload(request, view_url)
    return direct_to_template(request, 'add_photo.html',
                              {'form': form, 
                               'upload_url': upload_url,
                               'upload_data': upload_data})
Exemple #15
0
def edit_book(request, **kw):
    book_id = ZI(kw.get('id'))
    book = get_object_or_404(Book, id=book_id)
    if request.method == 'POST':
        form = AddBookForm(request.POST, request.FILES, instance=book)
        if form.is_valid():
            mbook = form.save(commit=False)
            if isinstance(request.user, User):
                mbook.author = request.user
            mbook.date = datetime.datetime.today()
            mbook.save(force_update=True)
            ClearBookListWrtCache(mbook.writer.id)
            ClearBookListSubjCache(mbook.subject.id)
            ClearBookCache(mbook.index)
            return HttpResponseRedirect(reverse('books.views.read_book', kwargs={'ind': mbook.index, 'part': 0}))
    else:
        form = AddBookForm(initial={
                           'id': book.id,
                           'title': book.title,
                           'content': book.content })
    upload_url, upload_data = prepare_upload(request, reverse('books.views.edit_book', kwargs={'id': book.id}))
    return render_to_response('edit_book.html', 
                              context_instance=RequestContext(request,
                              {'request': request,
                               'form': form,
                               'upload_url': upload_url,
                               'upload_data': upload_data,
                               'focus': form['content'].id_for_label}))
Exemple #16
0
def edit_book(request, **kw):
    book_id = ZI(kw.get('id'))
    book = get_object_or_404(Book, id=book_id)
    if request.method == 'POST':
        form = AddBookForm(request.POST, request.FILES, instance=book)
        if form.is_valid():
            mbook = form.save(commit=False)
            if isinstance(request.user, User):
                mbook.author = request.user
            mbook.date = datetime.datetime.today()
            mbook.save(force_update=True)
            ClearBookListWrtCache(mbook.writer.id)
            ClearBookListSubjCache(mbook.subject.id)
            ClearBookCache(mbook.index)
            return HttpResponseRedirect(reverse('books.views.read_book', kwargs={'ind': mbook.index, 'part': 0}))
    else:
        form = AddBookForm(initial={
                           'id': book.id,
                           'title': book.title,
                           'content': book.content })
    upload_url, upload_data = prepare_upload(request, reverse('books.views.edit_book', kwargs={'id': book.id}))
    return render_to_response('edit_book.html', 
                              context_instance=RequestContext(request,
                              {'request': request,
                               'form': form,
                               'upload_url': upload_url,
                               'upload_data': upload_data,
                               'focus': form['content'].id_for_label}))
Exemple #17
0
def upload_handler(request):
    view_url = reverse('handle_requests.views.upload_handler')
    # print view_url
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user_id = check_auth(username, password, request)
        # print "USER ID: " + str(user_id)
        if user_id is not -1:
            file_name = request.POST['file_name']
            size = request.POST['size']
            path = request.POST['path']
            form = UploadForm(request.POST, request.FILES)
            # print request.FILES
            # print request.POST
            form.save()
            file_object = File(name=file_name, path = path, user_id = user_id, size=size )
            file_object.save()
            mod = Modification(file_id = file_object.pk, user_id = user_id, mod_type='add')
            mod.save()
            return render(request, 'status.html', {'status': 'upload successful'})
        else:
            return render(request, 'status.html', {'status': 'login failure'})
    form = UploadForm()
    upload_url, upload_data = prepare_upload(request, view_url)
    # print upload_url
    # print upload_data
    return render(request, 'handle_requests/upload.html',
                  {'form': form, 'upload_url': upload_url, 'upload_data': upload_data})
def upload(request, class_name, id):
    form = None
    instance = get_class(class_name).objects.get(pk=id)
    view_url = reverse('portal.files.views.upload', args=[class_name, id, ])

    if request.method == 'POST':
        form = UploadedFileForm(request.POST, request.FILES)
        if form.is_valid():

            file = form.save(commit=False)
            file.content_type = ContentType.objects.get_for_model(instance)
            file.object_pk = force_unicode(instance._get_pk_val())
            file.user = request.user

            file.save()

            instance.notify_upload(request.user, file)
            
            return HttpResponseRedirect(instance.get_absolute_url())
    else:
        form = UploadedFileForm()

    upload_url, upload_data = prepare_upload(request, view_url)

    ctx = {
        'form': form,
        'upload_url': upload_url,
        'upload_data': upload_data,
    }

    return direct_to_template(request, 'files/form.html', ctx)
Exemple #19
0
def uploadRobotErrors(request):

    view_url = '/upload_robot_errors/'
    upload_url, upload_data = prepare_upload(request, view_url)
    if request.method=='POST':
        form = UploadForm (request.POST, request.FILES) #bound form to project
        if form.is_valid():
            f=form.save()
            f.save()#save for reuse
            for line in f.file:
                params = line.split(' ### ')
                msg_id = params[0]
                msg_value = params[1]
                time_stamp_script = params[2]
                time_stamp_error = params[3].strip()
                struct_time_script = datetime.strptime(time_stamp_script, "%Y-%m-%d %H:%M:%S")
                try:
                    time_stamp = datetime.strptime(time_stamp_error, "%Y-%m-%d %H:%M:%S")
                except Exception as e:
                    time_stamp = struct_time_script
                try:
                    robotError ,created = RobotError.objects.get_or_create(msg_id=msg_id,msg_value=msg_value,
                    script_time=struct_time_script,timeStamp = time_stamp)
                except Exception as e:
                    pass
            return HttpResponseRedirect('/')
    else:
        form = UploadForm()
        return direct_to_template(request, 'uploadErrors.html',
            { 'form':form,
              'upload_data':upload_data,
              })
Exemple #20
0
def experimentpage(request, exp_id,comesFromNewExp=False):
    view_url = '/experiments/'+exp_id
    #uploadFormForLiquidClasses = UploadForm()
    is_valid = False
    try:
        exp = Experiment.objects.get(pk = exp_id)
    except Exception as e:
        raise Http404
    if not request.user.is_authenticated():
         return index(request,message = 'user is not logged in')
    if request.method=='POST':
        f = ExperimentForm (request.POST,request.FILES,instance=exp)
        if f.is_valid() :
            is_valid = True
            exp = f.save()
    else:
        f= ExperimentForm(instance=exp)
        f.fields["liquidClass"].queryset = LiquidClass.objects.all().order_by('name')
    _man = exp.manualFile.file.file
    _rob = exp.robotFile.file.file
    dilsList,pipetorsCV ,dilsListForLineChart= compareManualToRobotReaderForWebApp(manualExcelFile= _man,robotExcelFile=_rob, experiment=exp)
    upload_url, upload_data = prepare_upload(request, view_url)
    distance = abs(exp.getMeans()-exp.volume)
    c = RequestContext(request,{'exp':exp,'exp_id':exp_id,'form':f,'messege':'New experiment submitted successfully','pipetorsCV':pipetorsCV,'dilsList':dilsList,'dilsListForLineChart':dilsListForLineChart, 'upload_url':upload_url, 'upload_data':upload_data,
                                'comesFromNewExperiment':False,'distance':distance})
    c.update(csrf(request))
    return render_to_response('experiment_page.html',c)
Exemple #21
0
def show_gig(request, band_id, entry_id):
    context = {}
    try:
        band = bands_manager.get_band(band_id)
        if not band.is_member(request.user):
            raise Exception("You have no permission to view this band's events cause you are not a member of it.")

        gig = bands_manager.get_gig(entry_id)

        # calculates the band diff setlist (band setlist songs minus gig setlist songs)
        diff_setlist = []

        for song in band.setlist.song_list:
            if not gig.setlist.contains(song):
                diff_setlist.append(song)

        context['diff_setlist'] = diff_setlist

        context['band'] = band
        context['gig'] = gig

        if gig.contract is None:
            view_url = reverse('project.views_gig.upload_contract', args=[band.id, gig.id])
            upload_url, upload_data = prepare_upload(request, view_url)
            context["contract_form"] = UploadBandFileForm()
            context['contract_url'] = upload_url
            context['contract_data'] = upload_data
            context['form'] = True
        else:
            context["contract"] = gig.contract
            context['form'] = False
    except Exception as exc:
        # 500
        context['error_msg'] = "Error ocurred: %s" % exc.message
    return render_to_response('band/events/gig/show.html', context, context_instance=RequestContext(request))
def detail(request, inst_slug, course_slug, disc_slug):
    institution = get_object_or_404(Institution, slug__exact=inst_slug)
    course = institution.course_set.get(slug__exact=course_slug)
    disc = course.discipline_set.get(slug__exact=disc_slug)

    msg_form = MessageForm(disc)
    upload_url, upload_data = prepare_upload(request, reverse("portal.messages.views.attach_file"))

    ctx = {
        "request": request,
        "discipline": disc,
        "photo_count": 0,
        "course": course,
        "institution": institution,
        "files": UploadedFile.objects.for_model(disc).order_by("date_published").all(),
        "next": reverse("portal.disciplines.views.detail", args=[inst_slug, course_slug, disc_slug]),
        "msg_form": msg_form,
        "attach_form": AttachmentForm(),
        "upload_url": upload_url,
        "upload_data": upload_data,
        "MODERATE_REGISTRATION": disc.registration_type == MODERATE_REGISTRATION,
        "EVERYONE_CAN_REGISTER": disc.registration_type == EVERYONE_CAN_REGISTER,
        "PUBLIC_ACCESS": disc.access_type == PUBLIC_ACCESS,
    }

    albums = Album.objects.for_model(disc)
    if albums.exists():
        ctx["albums"] = albums.all()
        qtd = 0
        for album in albums:
            qtd += album.picture_album_set.count()
        ctx["photo_count"] = qtd

    return direct_to_template(request, "disciplines/detail.html", ctx)
Exemple #23
0
def index(request):
    """first page. will show a nice UI and an imagefield."""
    # preparing the app engine specific crap.
    view_url = reverse('main.views.show_image')
    upload_url, upload_data = prepare_upload(request, view_url)
    form = forms.UploadForm()
    return render_to_response('index.html',
            {'form': form, 'upload_url': upload_url, 'upload_data': upload_data},
            context_instance=RequestContext(request))
Exemple #24
0
def __prepare_context(request, band):
    context = {}
    context['band'] = band
    view_url = reverse('upload-band-file', args=[band.id])
    upload_url, upload_data = prepare_upload(request, view_url)
    context['upload_form'] = UploadBandFileForm()
    context['upload_url'] = upload_url
    context['upload_data'] = upload_data
    return context
Exemple #25
0
def upload_handler(request):
    view_url = '/upload/'
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        form.save()
        return HttpResponseRedirect(view_url)
    upload_url, upload_data = prepare_upload(request, view_url)
    form = UploadForm()
    return direct_to_template(request, 'upload.html',
        {'form': form, 'upload_url': upload_url, 'upload_data': upload_data})
Exemple #26
0
 def get(self, request, *args, **kwargs):
     log.debug("in PhotoUploadView.get: args=%s, kwargs=%s"%(args, kwargs))
     target_url = reverse('photo-upload-user', kwargs={'pk':kwargs['pk'],'user_id':self.user.id})
     log.debug("Target URL: %s"%(target_url,))
     upload_url, upload_data = prepare_upload(request, target_url)
     log.debug("Upload URL: %s"%(upload_url,))
     #upload_url = blobstore.create_upload_url(target_url)
     result = {'upload_url':upload_url, 'target_url': target_url}
     log.debug("Result: %s"%(result,))
     return result
def __prepare_context(request, band, song):
    context = {}
    context["band"] = band
    context["song"] = song
    view_url = reverse("upload-song-file", args=[band.id, song.id])
    upload_url, upload_data = prepare_upload(request, view_url)
    context["song_form"] = UploadBandFileForm()
    context["song_url"] = upload_url
    context["song_data"] = upload_data
    return context
Exemple #28
0
def admin_bg_image(request):

    view_url = reverse('cms.views.admin_bg_image')

    if request.method == 'POST':

        form = BackgroundImageForm(request.POST, request.FILES)

        if form.is_valid():

            user = users.get_current_user()

            bg_image_form = form.save(commit=False)
            bg_image_form.author = user
            bg_image_form.file_name = request.FILES['image']
            bg_image_form.save()

            #bg_image_form.content_type = ('image/' + (str(request.FILES['image'])).partition('.')[2]).lower

            bg_image = BackgroundImage.objects.get(id=bg_image_form.id)
            blob_key = bg_image.image.file.blobstore_info.key()._BlobKey__blob_key 
            img = images.Image(blob_key=blob_key)
            bg_image.blob_key = blob_key
            bg_image.url = images.get_serving_url(blob_key)
            bg_image.url_thumb = images.get_serving_url(blob_key, 200)
            bg_image.save()

            #bg_image = BackgroundImage.objects.get(id=bg_image_form.id)

            #file_name = files.blobstore.create(mime_type='application/octet-stream')
            #with files.open(file_name, 'a') as f:
            #    f.write(bg_image.image)
            #files.finalize(file_name)
            #blob_key = files.blobstore.get_blob_key(file_name)

            #bg_image.thumb_content_type = ('image/png').lower

            #bg_image.save()

            return HttpResponseRedirect('/admin/bg_image?message=' + 'Updated')

    else:
        form = BackgroundImageForm()

    upload_url, upload_data = prepare_upload(request, view_url)
    form = BackgroundImageForm()
    #bg_images = BackgroundImage.objects.all().values('id', 'title', 'author', 'file_name', 'content_type', 'date_inserted' )
    bg_images = BackgroundImage.objects.all().values()

    return render_to_response('admin_bg_image.html', {
        'form': form, 
        'bg_images': bg_images,
        'upload_url': upload_url, 
        'upload_data': upload_data,
    }, context_instance=RequestContext(request))
Exemple #29
0
def add_book(request):
    if request.method == 'POST':
        form = AddBookForm(request.POST, request.FILES)
        form_wrt = AddWrtForm(request.POST)
        form_subj = AddSubjForm(request.POST)
        if form.is_valid() and form_wrt.is_valid() and form_subj.is_valid():
            book = form.save(commit=False)
            writer = form_wrt.save(commit=False)
            subject = form_subj.save(commit=False)
            for f in ['img', 'file']:
                if f in request.FILES: # check duplicates
                    if book.part == 0:
                        o = request.FILES[f]
                        for blob in blobstore.BlobInfo.gql("WHERE filename = '%s'"  % (o.name.replace("'","''"),)):
                            if blob.key() != o.blobstore_info.key(): blob.delete()
                    else:
                        book.file = None
                        book.img = None
            if isinstance(request.user, User):
                book.author = request.user
            # uniques
            book.index = abs(zlib.crc32(writer.writer.encode('utf-8') + ' ' + book.title.encode('utf-8')))
            # writer
            book_list = Book.objects.filter(index=book.index)
            if len(book_list): # check writer once
                wrt = book_list[0].writer
                subj = book_list[0].subject
            else:
                wrt = IncWrtCount(writer=writer.writer)
                subj = IncSubjCount(subject=subject.subject)
            book.writer = wrt
            book.subject = subj
            # if unique
            book_list = Book.objects.filter(Q(index=book.index)&Q(part=book.part))
            if len(book_list) == 0:
                book.save()
                ClearWrtListCache(wrt.writer[0].capitalize())
                ClearBookListWrtCache(wrt.id, wrt.count)
                ClearBookListSubjCache(subj.id, subj.count)
                ClearBookCache(book.index, book.part)
                return HttpResponseRedirect(reverse('books.views.list_books'))
    else:
        form = AddBookForm()
        form_wrt = AddWrtForm()
        form_subj = AddSubjForm()
    upload_url, upload_data = prepare_upload(request, reverse('books.views.add_book'))
    return render_to_response('add_book.html', 
                              context_instance=RequestContext(request,
                              {'request': request,
                               'form': form,
                               'form_wrt': form_wrt,
                               'form_subj': form_subj,
                               'upload_url': upload_url,
                               'upload_data': upload_data,
                               'focus': form_wrt['writer'].id_for_label}))
Exemple #30
0
def add_photo(request):
    if request.method == 'POST':
        form = AddPhotoForm(request.POST, request.FILES)
        if form.is_valid():
            photo = form.save(commit=False)
            try:
                if 'thumb_url' in form.data:
                    photo.thumb_url = form.data['thumb_url']
                if request.FILES.get('img'):
                    blob_key = request.FILES[
                        'img'].blobstore_info._BlobInfo__key
                    photo.thumb_url = images.get_serving_url(blob_key)
                    #                     data = blobstore.BlobReader(blob_key).read()
                    #                     img = images.Image(image_data=data)
                    o = request.FILES['img']
                    for blob in blobstore.BlobInfo.gql(
                            "WHERE filename = '%s'" %
                        (o.name.replace("'", "''"), )):
                        if blob.key() != o.blobstore_info.key(
                        ) and blob.md5_hash == o.blobstore_info.md5_hash:
                            blob.delete()
                if 'title1' in form.data:
                    photo.title = FromTranslit(form.data['title1'])
                if 'album1' in form.data:
                    photo.album = FromTranslit(form.data['album1'])
                if 'user' in form.data:
                    usr = User.objects.filter(username=form.data['user'])
                    if usr.count():
                        photo.author = usr[0]
                if isinstance(request.user, User):
                    photo.author = request.user
                photo.date = timezone.now()
                photo = form.save()
                ClearPhotosListCache(photo.album)
                UpdateAlbumListCache(photo)
                return HttpResponseRedirect(
                    reverse('my.views.list_photos',
                            kwargs={'id_album': photo.id}))
            except:
                pass
    else:
        form = AddPhotoForm()
    view_url = reverse('my.views.add_photo')
    upload_url, upload_data = prepare_upload(request, view_url)
    return render_to_response('add_photo.html',
                              context_instance=RequestContext(
                                  request, {
                                      'request': request,
                                      'form': form,
                                      'upload_url': upload_url,
                                      'upload_data': upload_data,
                                      'focus': form['title'].id_for_label
                                  }))
Exemple #31
0
def upload(request):
    view_url = reverse('gproject:upload')
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        form.save()
        return HttpResponseRedirect(view_url)

    upload_url, upload_data = prepare_upload(request, view_url)
    form = UploadForm()
    return render(request, 'gproject/upload.html',
        {'form': form, 'upload_url': upload_url, 'upload_data': upload_data,
         'uploads': UploadModel.objects.all()})
Exemple #32
0
def admin_bg_image_edit(request, bg_image_id=None):

    view_url = reverse('cms.views.admin_bg_image') #.'+bg_image_id)
    view_url = view_url + 'edit/' + str(bg_image_id) # FFS!

    if request.method == 'POST':

        bg_image = BackgroundImage.objects.get(id=bg_image_id)
        form = BackgroundImageForm(instance=bg_image, data=request.POST, files=request.FILES)

        if form.is_valid():

            user = users.get_current_user()

            bg_image_form = form.save(commit=False)
            bg_image_form.author = user

            if 'image' in request.FILES: #and request.FILES['image'] is True:
                bg_image_form.file_name = request.FILES['image']

            bg_image_form.save()

            bg_image = BackgroundImage.objects.get(id=bg_image_form.id)

            blob_key = bg_image.image.file.blobstore_info.key()._BlobKey__blob_key
            img = images.Image(blob_key=blob_key)
            bg_image.blob_key = blob_key
            bg_image.url = images.get_serving_url(blob_key)
            bg_image.url_thumb = images.get_serving_url(blob_key, 200)

            bg_image.save()

            key = 'bg_image_serve' + '-' + str(bg_image.id)
####            memcache.delete(key)

            ## TODO memcache.add() here
            ## Noel 07828 510 920

            return HttpResponseRedirect('/admin/bg_image/?message=' + urllib.quote_plus('Image has been updated') )

    else:

        bg_image = BackgroundImage.objects.get(id=bg_image_id)
        form = BackgroundImageForm(instance=bg_image)

        upload_url, upload_data = prepare_upload(request, view_url)

        return render_to_response('admin_bg_image_edit.html', {
            'form': form, 
            'bg_image': bg_image,
            'upload_url': upload_url, 
            'upload_data': upload_data,
        }, context_instance=RequestContext(request))
Exemple #33
0
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()})
Exemple #34
0
def add(request):
    if request.method == 'POST':
        formData = ArticleForm(request.POST, request.FILES)
        if formData.is_valid():
            edited = formData.save(commit=False)
            edited.user = request.user
            edited.save()
        return redirect("list")

    view_url = reverse("add")
    upload_url, upload_data = prepare_upload(request, view_url)

    return render(request, "add.html", {"form": ArticleForm, "action": "Add new", 'upload_url': upload_url, 'upload_data': upload_data})
Exemple #35
0
def upload_handler(request, obj_pk=None, ctype_pk=None):
    view_url = reverse('pirate_sources.views.upload_handler',
                       args=[obj_pk, ctype_pk])
    if request.method == 'POST':
        form = IMGSourceForm(request.POST, request.FILES)
        if form.is_valid():
            img = form.save()
            img.user = request.user
            img.object_pk = obj_pk
            img.content_type = ContentType.objects.get(pk=ctype_pk)
            img.submit_date = datetime.datetime.now()

            #file_content = ContentFile(request.FILES['file'].read())
            #img.file.save(str(img.object_pk) + '_' + str(img.content_type), file_content)
            img.make(request.FILES['file'], img.file.name)
            #photo_key = str(img.file.file.blobstore_info.key())
            url = img.file.path
            if img.private != True:
                try:
                    oldimg = IMGSource.objects.get(object_pk=obj_pk,
                                                   current=True)
                    oldimg.current = False
                    oldimg.save()
                except:
                    pass
                img.current = True
            img.url = url
            img.save()
        else:
            view_url += '?error=Not a valid image'
        return HttpResponseRedirect(view_url)

    upload_url, upload_data = prepare_upload(request, view_url)
    form = IMGSourceForm()

    uploads = IMGSource.objects.filter(object_pk=obj_pk)

    ctypemod = ContentType.objects.get(pk=ctype_pk)
    m = ctypemod.model_class()
    obj = m.objects.get(pk=obj_pk)
    return direct_to_template(
        request, 'upload.html', {
            'form': form,
            'upload_url': upload_url,
            'upload_data': upload_data,
            'object': obj,
            'uploads': uploads,
            'obj_pk': obj_pk,
            'ctype_pk': ctype_pk,
            'error': request.GET.get('error')
        })
Exemple #36
0
def upload_handler(request):
    view_url = reverse('upload.views.upload_handler')
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        form.save()
        return HttpResponseRedirect(view_url)

    upload_url, upload_data = prepare_upload(request, view_url)
    form = UploadForm()
    return render_to_response('upload/upload.html',
                              {'request': request,
                               'form': form,
                               'upload_url': upload_url,
                               'upload_data': upload_data})
Exemple #37
0
def upload_handler(request):
    view_url = reverse('upload.views.upload_handler')
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        form.save()
        return HttpResponseRedirect(view_url)

    upload_url, upload_data = prepare_upload(request, view_url)
    form = UploadForm()
    return render_to_response(
        'upload/upload.html', {
            'request': request,
            'form': form,
            'upload_url': upload_url,
            'upload_data': upload_data
        })
Exemple #38
0
def new_experiment(request):
    '''experiments = Experiment.objects.all().order_by('-startdate')[:5]
    tasks = Task.objects.all().order_by('-startdate')[:5]
    reagents = Reagent.objects.all().order_by('-createdate')[:5]
    plates = Plate.objects.all().order_by('-timestamp')[:5]'''
    is_valid = False
    is_post = False
    exp_id = 0
    view_url = '/new_experiment/'
    upload_url, upload_data = prepare_upload(request, view_url)
    if request.method=='POST':
        is_post = True
        form = ExperimentForm (request.POST, request.FILES) #bound form to project
        form.fields["liquidClass"].queryset = LiquidClass.objects.all().order_by('name')
        if form.is_valid():
            is_valid = True
            f=form.save(commit= False)
            f.user = request.user
            f=form.save(commit= True)
            exp = Experiment.objects.get(pk= f.id)
            exp_id = exp.id
           # uploadFileFromWebClient(request,exp,AMAZONE_URL,'manualFile')
            _man = f.manualFile.file.file
            _rob = f.robotFile.file.file
            dilsList,pipetorsCV ,dilsListForLineChart= compareManualToRobotReaderForWebApp(manualExcelFile= _man,robotExcelFile=_rob, experiment=exp)
            exp.grade = getAverageCV(pipetorsCV)
            exp.means = exp.getMeans()
            exp.distance = exp.getDistance()
            exp.save()
            distance = abs(exp.getMeans()-exp.volume)
            c = RequestContext(request,{'exp':exp,'exp_id':exp_id,'form':form,'messege':'New experiment submitted successfully','pipetorsCV':pipetorsCV,'dilsList':dilsList,'dilsListForLineChart':dilsListForLineChart,   'upload_url':upload_url,
                                        'upload_data':upload_data,'comesFromNewExperiment':True,'distance':distance})
            c.update(csrf(request))
            return render_to_response('experiment_page.html',c)
            #return HttpResponseRedirect('experiment_page.html',c)
    else:
        form = ExperimentForm()
        form.fields["liquidClass"].queryset = LiquidClass.objects.all().order_by('name')
        return direct_to_template(request, 'new_experiment.html',
            { 'form':form,
              'is_valid':is_valid,
              'is_post':is_post,
              'exp_id':exp_id,
              'upload_url':upload_url,
              'upload_data':upload_data,
              })
Exemple #39
0
def add_book(request):
    if request.method == 'POST':
        form = AddBookForm(request.POST, request.FILES)
        form_wrt = AddWrtForm(request.POST)
        form_subj = AddSubjForm(request.POST)
        if form.is_valid() and form_wrt.is_valid() and form_subj.is_valid():
            book = form.save(commit=False)
            writer = form_wrt.save(commit=False)
            subject = form_subj.save(commit=False)
            for f in ['file']:
                if f in request.FILES: # check duplicates
                    o = request.FILES[f]
                    for blob in blobstore.BlobInfo.gql("WHERE filename = '%s'"  % (o.name.replace("'","''"),)):
                        if blob.key() != o.blobstore_info.key(): blob.delete()
            if isinstance(request.user, User):
                book.author = request.user
            # uniques
            book.index = abs(zlib.crc32(writer.writer.encode('utf-8') + ' ' + book.title.encode('utf-8')))
            book_list = Book.objects.filter(Q(index=book.index))
            if len(book_list) == 0:
                book.writer = IncWrtCount(writer=writer.writer)
                book.subject = IncSubjCount(subject=subject.subject)
                book.save()
                ClearWrtListCache(book.writer.writer[0].capitalize())
                ClearBookListWrtCache(book.writer.id)
                ClearBookListSubjCache(book.subject.id)
                ClearBookCache(book.index)
                return HttpResponseRedirect(reverse('books.views.list_books'))
            else:
                edit_book(request, id=book_list[0].id)
    else:
        form = AddBookForm()
        form_wrt = AddWrtForm()
        form_subj = AddSubjForm()
    upload_url, upload_data = prepare_upload(request, reverse('books.views.add_book'))
    return render_to_response('add_book.html', 
                              context_instance=RequestContext(request,
                              {'request': request,
                               'form': form,
                               'form_wrt': form_wrt,
                               'form_subj': form_subj,
                               'upload_url': upload_url,
                               'upload_data': upload_data,
                               'focus': form_wrt['writer'].id_for_label}))
Exemple #40
0
def upload_handler(request):
    view_url = reverse('up5.upload_test.views.upload_handler')
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect(view_url)

    upload_url, upload_data = prepare_upload(request, view_url)
    form = UploadFileForm()
    print(request.user.social_auth.get().extra_data)
    return direct_to_template(
        request, 'upload2.html', {
            'form': form,
            'upload_url': upload_url,
            'upload_data': upload_data,
            'uploads': reversed(UploadFileModel.objects.all()),
            'user': request.user.social_auth.all()
        })
Exemple #41
0
def upload_handler(request):
    extra_data = request.user.social_auth.get()
    print(extra_data.extra_data)
    view_url = reverse('upload.views.upload_handler')
    names = request.user.social_auth.values_list('provider', flat=True)
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        form.save()
        return HttpResponseRedirect(view_url)

    upload_url, upload_data = prepare_upload(request, view_url, private=True)
    form = UploadForm()
    return direct_to_template(
        request, 'upload.html', {
            'form': form,
            'upload_url': upload_url,
            'upload_data': upload_data,
            'uploads': UploadModel.objects.all(),
            'names': names
        })
Exemple #42
0
def image_upload(request):
    view_url = reverse('blog.views.image_upload')
    if request.method == 'POST': # If the form has been submitted...
        form = ImageForm(request.POST, request.FILES) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            image = form.save()
            
            return HttpResponseRedirect('/image/info/' + str(image.pk)) # Redirect after POST

    else:
        form = ImageForm()
        
    upload_url, upload_data = prepare_upload(request, view_url)

    t = loader.get_template('image_upload.html')
    c = RequestContext(request,{
        'form': form,
        'title': 'Image Upload',
        'upload_url': upload_url, 
        'upload_data': upload_data
    })
    return HttpResponse(t.render(c))
Exemple #43
0
    def render_change_form(self,
                           request,
                           context,
                           add=False,
                           change=False,
                           form_url='',
                           obj=None,
                           has_file_field=True):
        opts = self.model._meta
        app_label = opts.app_label
        ordered_objects = opts.get_ordered_objects()

        if has_file_field:
            if not form_url:
                form_url = request.get_full_path()
            form_url, upload_data = prepare_upload(request, form_url)
            context.update({
                'file_upload_data':
                self.get_filetransfer_data(upload_data),
            })
        context.update({
            'add':
            add,
            'change':
            change,
            'has_add_permission':
            self.has_add_permission(request),
            'has_change_permission':
            self.has_change_permission(request, obj),
            'has_delete_permission':
            self.has_delete_permission(request, obj),
            'has_file_field':
            has_file_field,
            'has_absolute_url':
            hasattr(self.model, 'get_absolute_url'),
            'ordered_objects':
            ordered_objects,
            'form_url':
            mark_safe(form_url),
            'opts':
            opts,
            'content_type_id':
            ContentType.objects.get_for_model(self.model).id,
            'save_as':
            self.save_as,
            'save_on_top':
            self.save_on_top,
            'root_path':
            self.admin_site.root_path,
        })
        if add and self.add_form_template is not None:
            form_template = self.add_form_template
        else:
            form_template = self.change_form_template
        context_instance = template.RequestContext(
            request, current_app=self.admin_site.name)
        return render_to_response(form_template or [
            "admin/%s/%s/change_form.html" %
            (app_label, opts.object_name.lower()),
            "admin/%s/change_form.html" % app_label, "admin/change_form.html"
        ],
                                  context,
                                  context_instance=context_instance)