imagehost/imagehosting/views.py

59 lines
2.1 KiB
Python
Raw Normal View History

2017-09-27 13:35:32 +03:00
# -*- 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
2017-10-10 18:24:26 +03:00
from django.contrib.auth.decorators import login_required
2017-10-10 14:19:27 +03:00
from ih import images
2017-09-27 13:35:32 +03:00
from django.views.decorators.csrf import requires_csrf_token
def create_thumb_from_file(filename):
2017-10-10 14:19:27 +03:00
orig_file = 'imagehost/media/images/' + filename
# Create thumbnail
2017-09-27 13:35:32 +03:00
thumb_name = images.resize_image(orig_file, {
'name': filename,
'size': [300, 300],
2017-10-10 13:08:53 +03:00
'dest': 'imagehost/media/images'
2017-09-27 13:35:32 +03:00
}
)
2017-10-10 14:19:27 +03:00
return thumb_name
2017-09-27 13:35:32 +03:00
2017-10-11 19:01:22 +03:00
2017-10-10 18:24:26 +03:00
@login_required(login_url="/login")
2017-09-27 13:35:32 +03:00
def image_new(request):
if request.method == "POST":
form = PostForm(request.POST, request.FILES)
if form.is_valid():
post = form.save(commit=False)
post.save()
2017-10-10 14:19:27 +03:00
create_thumb_from_file(post.orig_name)
2017-10-10 13:08:53 +03:00
return redirect('imagehosting.views.image_detail', pk=post.id)
2017-09-27 13:35:32 +03:00
else:
form = PostForm()
2017-10-10 13:08:53 +03:00
return render(request, 'imagehosting/index.html', {'form': form})
2017-09-27 13:35:32 +03:00
2017-10-11 19:01:22 +03:00
2017-09-27 13:35:32 +03:00
def image_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
2017-10-10 13:08:53 +03:00
return render(request, 'imagehosting/image.html', {'post': post})
2017-09-27 13:35:32 +03:00
2017-10-11 19:01:22 +03:00
2017-09-27 13:35:32 +03:00
def all_posts(request):
all = Post.objects.order_by('-pk')
2017-10-10 13:08:53 +03:00
return render(request, 'imagehosting/all.html', {'all': all})
2017-09-27 13:35:32 +03:00
2017-10-10 14:19:27 +03:00
2017-10-10 18:24:26 +03:00
@login_required(login_url="/login")
2017-09-27 13:35:32 +03:00
def delete_post(request, pk):
post_to_delete = get_object_or_404(Post, pk=pk)
2017-10-10 18:24:26 +03:00
if request.method == 'GET':
2017-09-27 13:35:32 +03:00
form = DeleteForm(request.POST, instance=post_to_delete)
2017-10-10 14:19:27 +03:00
if form.is_valid(): # checks CSRF
2017-09-27 13:35:32 +03:00
if not request.user.is_authenticated():
return HttpResponseRedirect('/admin')
post_to_delete.delete()
2017-10-10 13:08:53 +03:00
return redirect('imagehosting.views.all_posts')
2017-10-11 19:01:22 +03:00
return render(request, 'imagehosting/delete.html', {'form': form})