예제 #1
0
def photographer_upload():
    # if request method is post
    if request.method == 'POST':
        form = PhotoUploadForm(name=request.form.get("name"),
                               file=request.files.get("file"))
        if form.validate():
            # get the photographer id from the user
            # save the image and link to photographer
            image_file = form.file.data
            photo = Photo(name=form.name.data,
                          photographer_id=current_user.photographer.id,
                          file=image_file.read())
            image = Image.open(image_file)
            file_type = image_file.headers.get("Content-Type")
            photo.add_image_data(*image.size, file_type)
            # save photo to db
            session_object = db_session()
            session_object.add(photo)
            session_object.commit()
            # success message
            flash("Image Uploaded Successfully", "success")
            return redirect(url_for('dashboard'))
        else:
            return render_template('photographer_uploads.html', form=form)
    # if the request is any other than get
    return render_template('photographer_uploads.html', form=PhotoUploadForm())
예제 #2
0
def profile_photo_upload(request):
    from forms import PhotoUploadForm
    error = False
    if request.method == 'POST':
        form = PhotoUploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(request.user)
        else:
            error = True
    else:
        form = PhotoUploadForm()
    return render_to_response('user/photo_upload.html',
                              { 'form' : form, 
                                'of_user' : request.user, 
                                'submit_button_text': 'Upload' },
                              context_instance=RequestContext(request))
예제 #3
0
def submitphotography(request):
    form = PhotoUploadForm(request.POST, request.FILES or None)
    if form.is_valid():
            pic = request.FILES['file']
            # [...] Process whatever you do with that file there. I resize it, create thumbnails, etc.
            # Get an instance of picture model (defined below) 
            picture = Picture()      
            picture.file = pic
            picture.pic_id = Picture.objects.all().count()
            picture.save()
            new_id=Art.objects.count()+1
	    phototext = picture.file
	    newphoto= Art(text=phototext, category="photography", art_id=new_id)
	    newphoto.save()
            return HttpResponse('Image upload succeeded.')
    return render(
	    request, 'artbase/submitphotography.html')
예제 #4
0
def upload_picture(request, uid=None):
    """
    Photo upload / dropzone handler
    :param request:
    :param uid: Optional picture UID when re-uploading a file.
    :return:
    """
    form = PhotoUploadForm(request.POST, request.FILES or None)
    if form.is_valid():
        pic = request.FILES['file']
        # [...] Process whatever you do with that file there. I resize it, create thumbnails, etc.
        # Get an instance of picture model (defined below) 
        picture = Picture()      
        picture.file = pic
        picture.pic_id = Picture.objects.all().count()
        picture.save()
        return HttpResponse('Image upload succeeded.')
    return HttpResponseBadRequest("Image upload form not valid.")
예제 #5
0
def upload_picture(request, uid=None):
    """
    Photo upload/dropzone handler
    :param request:
    :pram uid: Optional picture UID when re-uploading a file.
    : return:
    """

    form = PhotoUploadForm(request.POST, request.FILES or None)
    if form.is_valid():
        pic = request.FILES['file']
        # Process whatever to do with the file, resize, thumbnail etc.
        # Get an instance of picture model (defined below)
        # picture = ...
        picture.file = pic
        picture.save()
        return HttpResponse('Image upload successful.')
    return HttpResponseBadRequest("Image upload form not valid.")
예제 #6
0
def photo_upload(request, username):
    from django.template.loader import render_to_string
    from forms import PhotoUploadForm
    error = False
    if request.user.username != username:
        return render_noperm_response()
    if request.method == 'POST':
        form = PhotoUploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(request.user)
            return redirect( reverse('mentortogether.user.views.profile_view', kwargs={'username':username}) )
        else:
            error = True
    else:
        form = PhotoUploadForm()
    return render_to_response('user/photo_upload.html', { 'form' : form, 
                                                          'of_user' : request.user,
                                                          'submit_button_text' :  'Upload' },
                              context_instance=RequestContext(request))
예제 #7
0
def results():
    if (current_user.is_anonymous):
        return redirect(url_for('login'))

    form = PhotoUploadForm()

    # photo upload works, but doesn't save the file yet, this is being worked on
    if (request.method == 'POST'):
        photo = request.files['photo']

        mlsnums = closestMatches(photo)

        properties = {}
        top = {}
        count = 0

        for mlsnum in mlsnums:
            prop = Properties.query.filter_by(mlsnum=mlsnum).first()

            price = str(prop.listprice)
            p = str(prop.beds) + " beds | " + str(
                prop.baths) + " baths | " + str(int(prop.sqft)) + " sqft"

            # reformat the price string so it removes decimals and adds the price sign
            if (price is not None):
                sub = str(price).split(".")[0]
                price = "${:,}".format(int(sub))

            if count == 0:

                # separate out the 'top' hit to be displayed separately
                top[prop.mlsnum] = {
                    "string": p,
                    "photo": prop.photourl,
                    "mlsnum": mlsnum
                }

                if (price is not None):
                    top[prop.mlsnum].update({"price": price})
            else:
                properties[prop.mlsnum] = {
                    "string": p,
                    "photo": prop.photourl,
                    "mlsnum": mlsnum
                }

                if (price is not None):
                    properties[prop.mlsnum].update({"price": price})
            count = count + 1

        print(str(top))
        return render_template('results.html', properties=properties, top=top)
    else:
        return render_template('search.html', form=form)
예제 #8
0
def add_picture(request):
    if request.method == 'GET':
        return render(request, 'PicShare/uploadform.html', {
            'form': PhotoUploadForm,
            'user': request.user
        })

    if request.method == 'POST':
        form = PhotoUploadForm(request.POST, request.FILES)
        if form.is_valid():
            owner = request.user
            pic = Picture(owner=owner,
                          caption=form.data['caption'],
                          description=form.data['description'],
                          image=request.FILES['image'])
            pic.save()
            return HttpResponseRedirect(reverse('profile'))
        else:
            return render(request, 'PicShare/uploadform.html', {
                'form': form,
                'user': request.user
            })
예제 #9
0
def upload_profile_photo(request, username):
    person = get_object_or_404(DjangoPerson, user__username = username)
    if request.method == 'POST':
        form = PhotoUploadForm(request.POST, request.FILES)
        if form.is_valid():
            # Figure out what type of image it is
            image_content = request.FILES['photo']['content']
            format = Image.open(StringIO(image_content)).format
            format = format.lower().replace('jpeg', 'jpg')
            filename = md5.new(image_content).hexdigest() + '.' + format
            # Save the image
            path = os.path.join(settings.MEDIA_ROOT, 'profiles', filename)
            open(path, 'w').write(image_content)
            person.photo = 'profiles/%s' % filename
            person.save()
            return HttpResponseRedirect('/%s/upload/done/' % username)
    else:
        form = PhotoUploadForm()
    return render(request, 'upload_profile_photo.html', {
        'form': form,
        'person': person,
    })
예제 #10
0
파일: main.py 프로젝트: g----/barca
def admin(category=None):
    form = None
    data = {}

    if session.get('logged_in'):

        data['form'] =  PhotoUploadForm()
        data['categories'] = _get_categories()

        if request.method == 'POST':
            if request.form.get('add-category') is not None:
                title = request.form['title']
                exist = _get_category(urlize(title))

                if exist:
                    flash("Kategorie '%s' uz existuje." % title, 'error')
                else:
                    db.query("""
                        INSERT INTO category (title, url)
                        VALUES (?, ?)
                        """, (title, urlize(title)))

                    db.commit()
                    flash("Category '%s' saved" % title)
                    return redirect(url_for('admin'))
                #endif
            elif request.form.get('crop-photo') is not None:
                form = PhotoUploadForm(request.form)
                if form.validate():
                    photo = request.files.get('photo')
                    category = form.category.data

                    _c = _get_category(category)

                    filename = photos.save(photo, folder=_c['url'], name=app.config['TEMPORARY_FILENAME'])
                    session['photo_filename'] = filename

                    crop_form = PhotoForm()
                    crop_form.title.data = form.title.data
                    crop_form.description.data = form.description.data
                    crop_form.category.data = category
                    crop_form.category_url.data = _c['url']

                    data['form'] = crop_form
                    data['crop'] = True
                    data['filename'] = filename
                else:
                    flash('Form is not valid', 'error')
                    data['form'] = form
                #endif
            elif request.form.get('save-cropped-photo') is not None or request.form.get('save-photo') is not None:
                crop = False
                if request.form.get('save-cropped-photo') is not None:
                    form = PhotoForm(request.form)
                    crop = True
                    category_url = form.category_url.data
                else:
                    form = PhotoUploadForm(request.form)
                    photo = request.files.get('photo')
                    category = form.category.data

                    _c = _get_category(category)
                    category_url = _c['url']

                    filename = photos.save(photo, folder=category_url, name=app.config['TEMPORARY_FILENAME'])
                    session['photo_filename'] = filename
                #endif

                if form.validate():
                    im_path = '%s/%s' % (app.config['UPLOADED_PHOTOS_DEST'], session['photo_filename'])
                    im = PILImage.open(im_path)
                    im = im.copy().convert('RGBA')

                    if crop:
                        try:
                            box = ( int(form.x1.data), int(form.y1.data), int(form.x2.data), int(form.y2.data))
                            cropped = im.crop(box)
                            cropped.thumbnail(app.config['IMAGE_SIZE'], PILImage.ANTIALIAS)
                        except ValueError:
                            # Spadne sem pokud pri save-cropped-photo neni zadan crop
                            # Dopocitat pruhy + resize
                            cropped = save_resized_image(im.copy())
                        #endtry
                    else:
                        # Spadne sem pri save-photo
                        # Dopocitat pruhy + resize
                        cropped = save_resized_image(im.copy())
                    #enddef

                    db.query("""
                        INSERT INTO photo
                            (title, description, category_id)
                        VALUES (?, ?, ?)
                        """, (form.title.data, form.description.data, form.category.data))

                    db.commit()

                    # Save crop
                    new_im_path = '%s/%s/%s.png' % (app.config['UPLOADED_PHOTOS_DEST'], category_url, db.lastrowid)
                    cropped.save(new_im_path)

                    # Cleanup
                    del(session['photo_filename'])
                    os.unlink(im_path)

                    flash('Photo saved.')
                    return redirect(url_for('admin'))
                else:
                    # TODO zachovani dat ve formulari
                    data['form'] = form
                    if crop:
                        data['crop'] = True
                        data['filename'] = session['photo_filename']
                    #endif
                    flash('Cannot save photo.', 'error')
                #endif
            elif request.form.get('delete-photo') is not None:
                photo = request.form.get('delete-photo')
                category = request.form.get('category')

                db.query("""
                    DELETE FROM photo
                    WHERE id = ?
                    """, (photo,))

                db.commit()
                flash('Photo deleted.')
                #data = {}
                #data['edit_category'] = True
                #data['photos'] = _get_photos(category)
                #data['category'] = _get_category(category)
                return redirect(url_for('admin', category=category))
            elif request.form.get('delete-category') is not None:
                category_id = request.form.get('delete-category')
                db.query("""
                    DELETE FROM photo
                    WHERE category_id = ?
                    """, (category_id,))

                db.query("""
                    DELETE FROM category
                    WHERE id = ?
                    """, (category_id,))
                db.commit()

                flash('Category deleted.')
                return redirect(url_for('admin'))
            #endif
        elif category is not None:
            data = {}
            data['edit_category'] = True
            data['photos'] = _get_photos(category)
            data['category'] = _get_category(category)
        #endif
    else:
        data['form'] = LoginForm()
    #endif
    return render_template('admin.html', **data)