imagehost/imagehosting/views.py
2017-09-27 14:12:01 +03:00

94 lines
3.0 KiB
Python

# -*- coding: utf-8 -*-
from django.shortcuts import render, get_object_or_404, HttpResponseRedirect
from .models import Post
from .forms import PostForm, DeleteForm
from django.shortcuts import redirect
from ih import files, images
from django.views.decorators.csrf import requires_csrf_token
'''def create_thumbnail(request):
# Get file from <InMemoryUploadedFile>
file_l, filename = files.get_file_from_request(request, 'file')
fh = files.write_to_shm(file_l, filename)
file_l = None
# Create thumbnail
thumb_name = images.resize_image(fh, {
'name': filename,
'size': (100, 100),
'dest': 'mysite/media/images'
}
)
print(thumb_name)
# Remove file from shm
e = files.rm_from_shm(filename)
if e is not True:
print "WARNING: " + e
return thumb_name'''
def create_thumb_from_file(filename):
orig_file = 'mysite/media/images/' + str(filename)
print(filename)
# Create thumbnail
print("DEBUG: Resizing image " + orig_file)
thumb_name = images.resize_image(orig_file, {
'name': filename,
'size': [300, 300],
'dest': 'mysite/media/images'
}
)
return thumb_name
def image_new(request):
if request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
# thumb_name = create_thumbnail(request)
post = form.save(commit=False)
post.save()
print("FILE: ", post.file)
create_thumb_from_file(post.orig_name)
return redirect('imagehost.views.image_detail', pk=post.id)
else:
form = PostForm()
return render(request, 'imagehost/index.html', {'form': form})
def image_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
print(post)
return render(request, 'imagehost/image.html', {'post': post})
def all_posts(request):
all = Post.objects.order_by('-pk')
page = request.POST.get("page")
return render(request, 'imagehost/all.html', {'all': all})
def carousel(request):
return render(request, 'imagehost/carousel.html', {'all': Post.objects.all()})
@requires_csrf_token
def delete_post(request, pk):
post_to_delete = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = DeleteForm(request.POST, instance=post_to_delete)
if form.is_valid(): # checks CSRF
if not request.user.is_authenticated():
return HttpResponseRedirect('/admin')
post_to_delete.delete()
return redirect('imagehost.views.all_posts')
else:
form = DeleteForm(instance=post_to_delete)
return render(request, 'imagehost/delete.html', {'form': form})