Example #1
0
def images_add(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/staff/login/')
    elif request.user.has_perm('images.add_image'):
        if request.method == 'POST':
            form = ImageForm(request.POST, request.FILES)
            if form.is_valid():
                # save new image
                new_image = Image(name=form.cleaned_data['name'])
                if form.cleaned_data.get('caption'):
                    new_image.caption = form.cleaned_data['caption']
                if form.cleaned_data.get('credit'):
                    new_image.credit = form.cleaned_data['credit']
                new_image.image = form.cleaned_data['image']
                new_image.save()
                return HttpResponseRedirect(
                    reverse('images.views.images_add_to_markup',
                            args=[new_image.id]))
            else:
                return render_to_response(
                    'images/widget_add.html', {'form': form},
                    context_instance=RequestContext(request))
        else:
            form = ImageForm()
            return render_to_response('images/widget_add.html', {'form': form},
                                      context_instance=RequestContext(request))
    else:
        return render_to_response('staff/access_denied.html', {
            'missing': 'add photos to',
            'staffapp': 'this entry'
        },
                                  context_instance=RequestContext(request))
Example #2
0
def edit_image(request, image_id):

    if not request.user.is_authenticated:
        messages.error(request, 'Kirjaudu siään muokataksesi kuvia')
        return redirect('/')

    image = Image.objects.get(id=image_id)

    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES, instance=image)

        if form.is_valid():

            image.name = form.cleaned_data['name']
            image.description = form.cleaned_data['description']

            try:
                if request.FILES['pic']:
                    image.pic = request.FILES['pic']
            except Exception as e:
                print(e)

            messages.success(request, 'Kuvaa muokattiin onnistuneesti')

    else:
        form = ImageForm(None, instance=image)

    return render(request, 'edit_image.html', {'form': form})
Example #3
0
def images(request, username, rows_show=4):
    form_mess = MessageForm()
    try:
        profile_user = UserProfile.objects.get(username=username)
    except UserProfile.DoesNotExist:
        raise Http404

    is_visible = profile_user.check_visiblity('profile_image', request.user)
    if not is_visible:
        raise Http404

    ctype = ContentType.objects.get_for_model(UserProfile)
    qs = Image.objects.filter(owner_type=ctype, owner_id=profile_user.id)
    manage_perm = request.user == profile_user

    if request.method == 'POST' and manage_perm:
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            image = form.save(profile_user)
            image.make_activity()
            image.generate_thumbnail(200, 200)
            image.change_orientation()
            # try:
            #     pil_object = pilImage.open(image.image.path)
            #     w, h = pil_object.size
            #     x, y = 0, 0
            #     if w > h:
            #         x, y, w, h = int((w-h)/2), 0, h, h
            #     elif h > w:
            #         x, y, w, h = 0, int((h-w)/2), w, w
            #     new_pil_object = pil_object \
            #         .crop((x, y, x+w, y+h)) \
            #         .resize((200, 200))
            #     new_pil_object.save(image.image.thumb_path)
            # except:
            #     pass
            return redirect('profile.views.images',
                            username=profile_user.username)
    else:
        form = ImageForm()

    return render_to_response(
        'profile/images.html', {
            'profile_user': profile_user,
            'form': form,
            'form_mess': form_mess,
            'image_rows': qs.get_rows(0, rows_show),
            'total_rows': qs.total_rows(),
            'photos_count': qs.count(),
            'manage_perm': manage_perm,
        }, RequestContext(request))
Example #4
0
def model_form_upload(request):

    # Code obtained and modified from:
    # https://github.com/sibtc/simple-file-upload
    # Original Author: https://github.com/sibtc

    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = ImageForm()
    return render(request, 'images/model_form_upload.html', {'form': form})
Example #5
0
def update_wish(request, animal_id):
    from images.forms import ImageForm
    # Get active wish from animal's set
    # GET returns form to upload images (no other attribute changes)
    # POST adds images and triggers mailer to send email with images to donor

    animal = Animal.objects.get(pk=animal_id)
    wish = animal.get_active_wish()
    form = ImageForm(request.POST, request.FILES)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
            # img_obj = Image.objects.create(upload=request.POST['upload'])
            img_obj = form.instance
            wish.images.add(img_obj)

            # Get list of address and send email to each one
            d_set = wish.donation_set.all()
            for d in d_set:
                mailer.send_wish_imgs(d)

            # Get the current instance object to display in the template
            return render(request, 'animals/wish_form.html', {
                'form': form,
                'img_obj': img_obj
            })
    else:
        return render(request, 'animals/wish_form.html', {
            'wish': wish,
            'form': form
        })
Example #6
0
def add_image(request):

    if not request.user.is_authenticated:
        messages.error(request, 'Kirjaudu siään lisätäksesi kuvia')
        return redirect('/')

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

        if form.is_valid():
            image = form.save(commit=False)
            image.uploader = request.user.id

            try:
                pic = request.FILES['pic']
                image.pic = pic

                # image_file = io.StringIO(pic.read())
                # pil_image = PilImage.open(image_file)
                # w, h = pil_image.size
                #
                # pil_image = pil_image.resize((w/4, h/4), PilImage.ANTIALIAS)
                # image_file = io.StringIO()
                # pil_image.save(image_file, 'PNG', quality=90)
                #
                # image.compressed_pic = image_file

            except Exception as e:
                print(e)
                messages.info(request,
                              'Kuvalle ei annettu kuvaa, käytetään oletusta.')
                print("No pic provided, using default image.")

            image.views = 0
            image.save()

            album = Album.objects.get(pk=request.POST['album'])
            album.images.add(image)
            album.save()
            form = ImageForm()

            messages.success(request, 'Kuva ladattiin onnistuneesti!')

    else:
        form = ImageForm()

    return render(request, 'add_image.html', {'form': form})
Example #7
0
def create(request):
    form = ImageForm(request.POST, request.FILES)

    if form.is_valid():
        form.save()
        return redirect('images:index')

    return redirect('images:new')
Example #8
0
def save(request):
    #import pudb; pudb.set_trace()
    data = {'status': 'OK'}
    if request.method == 'POST' and 'content' in request.POST:
        user_to = None
        if 'profile_id' in request.POST:
            user_to = UserProfile.objects.get(id=request.POST['profile_id'])
        post = ContentPost(content=request.POST['content'],
                           user=request.user,
                           user_to=user_to)
        if 'type' in request.POST:
            post.type = request.POST['type']
        else:
            post.type = 'P'
        post.save()

        # attach uploaded images
        rotation = request.POST.getlist('image_rotation')
        i = 0
        for image in request.FILES.getlist('image'):
            image_form = ImageForm(None, {'image': image})
            rotate = rotation[i]
            i += 1
            if image_form.is_valid():
                img = image_form.save(post)
                # img.make_activity()
                if rotate:
                    rotate = int(rotate)
                    rotate = (rotate * 90 * -1) % 360
                    img.generate_thumbnail(200, 200, angle=rotate)
                    img.generate_thumbnail(262,
                                           262,
                                           angle=rotate,
                                           size='medium')
                    img.generate_thumbnail(530,
                                           530,
                                           angle=rotate,
                                           size='large')
                    img.change_orientation(rotate)
                else:
                    img.generate_thumbnail(200, 200)
                    img.generate_thumbnail(262, 262, size='medium')
                    img.generate_thumbnail(530, 530, size='large')
                    img.change_orientation()
            else:
                data['status'] = 'fail'
                data['errors'] = image_form.errors
                break

        #Tags
        hashtags = list_tags(request.POST['content'])

        for hashtag in hashtags:
            try:
                tag = Tag.objects.get(name__iexact=hashtag)
                post.tags.add(tag)
            except ObjectDoesNotExist:
                post.tags.create(name=hashtag)
            except MultipleObjectsReturned:
                tags = Tag.objects.filter(name__iexact=hashtag)
                tag = [p for p in tags if not hasattr(p, 'user_tag')]
                if tag:
                    post.tags.add(tag[0])

        data['post_id'] = post.id

        t = loader.get_template('post/_feed.html')
        new_post = post
        c = RequestContext(request, {
            'items': [new_post],
            'post_user': post.user,
            'del_false': True
        })
        data['html'] = t.render(c)

    return HttpResponse(json.dumps(data), "application/json")
Example #9
0
def profile(request, username):
    try:
        profile_user = UserProfile.objects.get(username=username)
    except UserProfile.DoesNotExist:
        raise Http404

    form_mess = MessageForm()
    cover_form = ImageCoverForm()
    form_mess.fields['content'].widget.attrs['rows'] = 7

    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)
        if request.user.is_authenticated() \
            and 'image' in request.POST \
                and form.is_valid():
            image = form.save(profile_user)
            image.make_activity()
            image.generate_thumbnail(200, 200)
            image.change_orientation()
            # try:
            #     pil_object = pilImage.open(image.image.path)
            #     w, h = pil_object.size
            #     x, y = 0, 0
            #     if w > h:
            #         x, y, w, h = int((w-h)/2), 0, h, h
            #     elif h > w:
            #         x, y, w, h = 0, int((h-w)/2), w, w
            #     new_pil_object = pil_object \
            #         .crop((x, y, x+w, y+h)) \
            #         .resize((200, 200))
            #     new_pil_object.save(image.image.thumb_path)
            # except:
            #     pass
            return redirect('profile.views.profile',
                            username=profile_user.username)

        if 'message' in request.POST:
            form_mess = MessageForm(request.POST)
            if form_mess.is_valid():
                user_to = profile_user
                content = form_mess.cleaned_data['content']
                mess = Messaging(user=request.user,
                                 user_to=user_to,
                                 content=content)
                mess.save()
                return HttpResponseRedirect(request.path)
    else:
        form = ImageForm()

    if request.method == 'GET' and 'albums' in request.GET:
        """Albums view"""
        return render_to_response(
            'profile/albums.html', {
                'profile_user': profile_user,
                'form_mess': form_mess,
                'albums': request.user.albums_set.all().order_by('position'),
            }, RequestContext(request))

    data_uri = ''
    restrict_height = 300
    target_width = 900
    resize = False
    if request.method == 'POST' \
            and 'cover_image' in request.POST:
        cover_form = ImageCoverForm(request.POST, request.FILES)
        if cover_form.is_valid():
            image = cover_form.cleaned_data['cover_photo']
            # save to memory
            f = StringIO(image.read())
            # PIL image
            img = pilImage.open(f)

            # reading and applying orientation
            for orientation in ExifTags.TAGS.keys():
                if ExifTags.TAGS[orientation] == 'Orientation': break
            try:
                exif = dict(img._getexif().items())
                if exif[orientation] == 3:
                    img = img.rotate(180, expand=True)
                elif exif[orientation] == 6:
                    img = img.rotate(270, expand=True)
                elif exif[orientation] == 8:
                    img = img.rotate(90, expand=True)
            except:
                pass

            (width, height) = img.size
            if width < target_width:
                target_height = int(height * (1.0 * target_width / width))
                img = img.resize((target_width, target_height))
            elif width > target_width:
                target_height = int(height * (1.0 * target_width / width))
                img.thumbnail((target_width, target_height),
                              pilImage.ANTIALIAS)
            else:
                pass
            (new_width, new_height) = img.size
            if new_height != restrict_height:
                resize = True
            # save to memory
            thumb = StringIO()
            img.save(thumb, 'JPEG')
            thumb.seek(0)
            thumb_file = InMemoryUploadedFile(thumb, None, image.name,
                                              image.content_type, thumb.len,
                                              image.charset)

            # we can save it
            #if page.cover_photo and page.cover_photo.name != page.cover_photo.field.default:
            #page.cover_photo.delete()
            if not resize:
                request.user.cover_photo = thumb_file
                request.user.save()
            # or we can return it to template

            class DataURI:
                def __init__(self):
                    self.width = 0
                    self.height = 0
                    self.data_uri = None

                def __repr__(self):
                    return self.data_uri

            data_uri = DataURI()
            data_uri.data_uri = 'data:image/jpg;base64,'
            data_uri.data_uri += thumb.getvalue().encode('base64').replace(
                '\n', '')
            data_uri.width = new_width
            data_uri.height = new_height

            image_height = data_uri.height

    if resize:
        cover_offset = (image_height - restrict_height - 45 - 95) * -1
        return render_to_response(
            'profile/profile_cover.html', {
                'profile_user': profile_user,
                'form': form,
                'cover_form': cover_form,
                'form_mess': form_mess,
                'cover_offset': cover_offset,
                'data_uri': data_uri,
                'profile_view': True,
            }, RequestContext(request))
    else:
        return render_to_response(
            'profile/profile.html', {
                'profile_user': profile_user,
                'form': form,
                'cover_form': cover_form,
                'form_mess': form_mess,
                'show_cover_form': True,
                'profile_view': True,
            }, RequestContext(request))
Example #10
0
def new(request):
    form = ImageForm()
    context = {'form': form}
    return render(request, 'images/new.html', context)