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 })
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))
def object_image_edit(request, content_type, object_id, id): try: obj = ContentType.objects.get(model=content_type).get_object_for_this_type(pk=object_id) if not obj.can_edit(request.user): raise Http404 img = obj.images.get(pk=id) except: raise Http404 if request.method == "POST": form = ImageForm(request.POST, request.FILES, instance = img) if form.is_valid(): form.save() return redirect(object_image_list, content_type=content_type, object_id=object_id) else: form = ImageForm(instance = img) return direct_to_template( request, template = "images/object_form.html", extra_context = { 'form': form, 'content_type': content_type, 'object_id': object_id } )
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})
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), )
def create(request): form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('images:index') return redirect('images:new')
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), )
def ImageInsert(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/login') profile = request.user.get_profile() '''saving the pic''' if request.method =="POST": image_form = ImageForm(request.POST, request.FILES, instance = profile) if image_form.is_valid(): image_form.save() #resize and save image under same filename image_file = pjoin(MEDIA_ROOT, user_reg.avatar.name) image = PImage.open(image_file) image.save(image_file, "JPEG") else: image_form = ImageForm(instance = profile) if profile.image: image = "/media/" + profile.image.name context = {"profile" : profile, "image_form" : image_form, "image":image, "media_url": MEDIA_URL} return render_to_response("upload.html", context, context_instance= RequestContext(request))
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})
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})
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))
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))
def new(request): form = ImageForm() context = {'form': form} return render(request, 'images/new.html', context)
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), )
def new(request, parent_id = None): parent = None save_mode = None if parent_id: parent = get_object_or_404(Post, pk = parent_id) form = PostForm( request.POST or None, request.FILES or None, author = request.user, parent = parent, ) image_form = ImageForm(request.POST or None, request.FILES or None) game_form = GameForm(request.POST or None, request.FILES or None) tag_form = TagForm(request.POST or None) if parent is None else None valid = False #A reply if parent is not None: valid = (parent is not None and form.is_valid()) #a new post: if parent is None: valid = (parent is None and form.is_valid() and tag_form.is_valid()) #an image post: if request.GET.get('image',False): save_mode = 'image' valid = (parent is None and form.is_valid() and tag_form.is_valid() and image_form.is_valid()) #a game post: if request.GET.get('game',False): save_mode = 'game' valid = (parent is None and form.is_valid() and tag_form.is_valid() and game_form.is_valid()) if valid: post = form.save() if parent is None: tag_form.post = post tag_form.save() if parent is None: PostReader.clear(post = post) else: PostReader.clear(post = post.parent) if image_form.is_valid() and save_mode == 'image': image_form.save(post = post) if game_form.is_valid() and save_mode == 'game': game_form.save(post = post) game_form.save_m2m() r_post = post if not parent else parent return redirect(reverse("posts:view", args=[r_post.id, r_post.title_slug()])) context = { 'form' : form, 'tag_form' : tag_form, 'image_form' : image_form, 'game_form' : game_form, } return render_to_response( "posts/post_form.html", context, RequestContext(request) )
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")
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")