def send_mail(request): if request.method == "POST": merrors = False additiveerror = "" mailform = MessageForm(request.POST) u = User.objects.get_by_natural_key(username=request.user.username) if mailform.is_valid(): try: u2 = User.objects.get_by_natural_key(username=mailform.cleaned_data["reciver"]) if not u2 == None: if u.username != u2.username: umail = Mail.objects.create(sender=request.user.username ,reciver=mailform.cleaned_data["reciver"] ,subject=mailform.cleaned_data['subject'] , message=mailform.cleaned_data['message']) umail.save() else: merrors = True additiveerror = "you cannot send mails to yourself" except ObjectDoesNotExist: merrors = True additiveerror = "destination user cannot be found" else: merrors = True return render(request , "mail.html" , {'form' : mailform , 'merrors' : merrors , 'additiveerror' : additiveerror}) else: uform = MessageForm() return render(request ,'mail.html' , {'form' :uform })
def messages_view(request): if not request.user.is_authenticated(): return redirect('login') if request.method == 'POST': form = MessageForm(data=request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] to = form.cleaned_data['to'] body = form.cleaned_data['body'] send_to = User.objects.filter(username=to) if send_to.count() != 0: msg = Message() msg.msg_from = request.user msg.msg_to = send_to[0] msg.body = body msg.subject = subject msg.save() messages.add_message(request, messages.SUCCESS, 'Message sent Successfully', extra_tags='alert-success') else: messages.add_message(request, messages.WARNING, 'User Does Not Exist.', extra_tags='alert-danger') else: messages.add_message(request, messages.WARNING, 'One or More Invalid Field(s).', extra_tags='alert-danger') return redirect('messaging:messages') template = loader.get_template('base_messages_inbox.html') message_q = Message.objects.filter(msg_to=request.user)[:50] if message_q.count() != 0: message_list = list(message_q) message_list.reverse() args = {'user_messages': message_list} else: args = {} context = RequestContext(request, args) return HttpResponse(template.render(context))
def send_message(request): base = BaseUser.objects.get(user=request.user) if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): m = form.cleaned_data['message'] r = (form.cleaned_data['receiver']).strip() form.validate() s = request.user.username p = form.cleaned_data['subject'] if r == s: return render( request, 'messaging/send_message.html', { 'form': MessageForm(), 'type': base.user_role, 'is_yourself': True }) # raise Error("cannot send a message to yourself") if form.cleaned_data['encrypt']: # encrypt receiver_user = User.objects.get(username=r) receiver_base_user = BaseUser.objects.get(user=receiver_user) receiver_RSAkey = RSA.importKey(receiver_base_user.RSAkey) m = str( receiver_RSAkey.encrypt(m.encode('utf-8'), "not needed".encode('utf-8'))[0]) message = Message.objects.create(subject=p, message=m, receiver=r, sender=s, encrypt=True) return render( request, 'messaging/send_message.html', { 'form': MessageForm(), 'type': base.user_role, 'is_yourself': False }) else: # leave as the same message = Message.objects.create(subject=p, message=m, receiver=r, sender=s, encrypt=False) return render( request, 'messaging/send_message.html', { 'form': MessageForm(), 'type': base.user_role, 'is_yourself': False }) else: form = MessageForm() return render(request, 'messaging/send_message.html', { 'form': form, 'type': base.user_role, 'is_yourself': False })
def send_message(request): sent_from = request.user if request.method == 'POST' and request.is_ajax(): form = MessageForm(request.POST) id = request.POST.get('name') send_to = User.objects.get(id=id) print send_to if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] new_message = Message(subject=subject, message=message, send_to=send_to, sent_from=sent_from, is_sent=True).save() return HttpResponse('sent') return HttpResponse('...')
def send_message(request, username): data = {'status': 'FAIL'} try: profile_user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: raise Http404 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() data['status'] = 'OK' return HttpResponse(json.dumps(data), "application/json")
def send_message(request, username): data = {"status": "FAIL"} try: profile_user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: raise Http404 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() data["status"] = "OK" return HttpResponse(json.dumps(data), "application/json")
def reply(request): sent_from = request.user #sent with ajax request if request.method == 'POST' and request.is_ajax(): new_message = MessageForm(request.POST) id = request.POST.get('name') #gets the message that this one is replying to old_message = Message.objects.get(id=id) #the old message's 'from' becomes this message's 'to' send_to = old_message.sent_from if new_message.is_valid(): subject = new_message.cleaned_data['subject'] message = new_message.cleaned_data['message'] new_msg = Message(send_to=send_to, sent_from=sent_from, subject=subject, message=message, is_sent=True) #indicates which message this one is replying to new_msg.is_reply = old_message new_msg.save() return HttpResponse('sent') return HttpResponse('...')
def messages_view(request): if not request.user.is_authenticated(): return redirect('sharetools:login') if request.method == 'POST': form = MessageForm(data=request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] to = form.cleaned_data['to'] body = form.cleaned_data['body'] send_to = User.objects.filter(username=to) if send_to.count() != 0: msg = Message() msg.msg_from = request.user msg.msg_to = send_to[0] msg.body = body msg.subject = subject msg.save() messages.add_message(request, messages.SUCCESS, 'Message sent Successfully', extra_tags='alert-success') else: messages.add_message(request, messages.WARNING, 'User Does Not Exist.', extra_tags='alert-danger') else: messages.add_message(request, messages.WARNING, 'One or More Invalid Field(s).', extra_tags='alert-danger') return redirect('messaging:messages') template = loader.get_template('base_messages_inbox.html') message_q = Message.objects.filter(msg_to=request.user)[:50] if message_q.count() != 0: message_list = list(message_q) message_list.reverse() args = {'user_messages': message_list} else: args = {} context = RequestContext(request, args) return HttpResponse(template.render(context))
def related_users(request, username): form_mess = MessageForm() if not username: profile_user = request.user else: try: profile_user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: raise Http404() if request.method == 'GET': data = {} users = [] if 'Friends' in request.GET and profile_user.check_visiblity( 'friend_list', request.user): friends = profile_user.get_friends() """ if friends: friends = friends.exclude(id=request.user.id) """ users.extend(friends) data['html'] = [x.username for x in friends] if 'Following' in request.GET and profile_user.check_visiblity( 'following_list', request.user): following = profile_user.get_following_active(request.user) users.extend(following) data['html'] = [x.username for x in following] if 'Followers' in request.GET and profile_user.check_visiblity( 'follower_list', request.user): followers = profile_user.get_followers_active(request.user) users.extend(followers) data['html'] = [x.username for x in followers] if users: # custom ordering users = list(set(users)) users = sorted(users, key=lambda s: s.get_full_name()) if len(data) > 0 and 'ajax' in request.GET: data['html'] = render_to_string( 'profile/related_users.html', { 'current_user': profile_user, 'users': users, }, context_instance=RequestContext(request)) return HttpResponse(json.dumps(data), "application/json") return render_to_response( 'profile/related.html', { 'profile_user': profile_user, 'current_user': request.user, 'form_mess': form_mess, 'users': users, }, RequestContext(request))
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 albums(request, username): """Albums view""" form_mess = MessageForm() try: profile_user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: raise Http404 return render_to_response( 'profile/albums.html', { 'profile_user': profile_user, 'form_mess': form_mess, 'albums': profile_user.albums_set.all().order_by('position'), 'album_view': True, }, RequestContext(request))
def loves(request, username): data = {} form_mess = MessageForm() if not username: profile_user = request.user else: try: profile_user = UserProfile.objects.get(username=username) except UserProfile.DoesNotExist: raise Http404() pages = profile_user.get_loved() if request.method == 'GET' and 'ajax' in request.GET: if 'business' in request.GET and not 'nonprofit' in request.GET: pages = pages.filter(type='BS') if 'nonprofit' in request.GET and not 'business' in request.GET: pages = pages.filter(type='NP') if 'posts' in request.GET: pages = profile_user.get_loved_posts() pages = sorted(pages, key=lambda item: PageLoves.objects.get( page=item, user=request.user).date if isinstance(item, Pages) else PostLoves.objects. get(post=item, user=profile_user).date, reverse=True) page_type = 'news_feed' data['html'] = render_to_string( 'post/_feed.html', { 'profile_user': profile_user, 'items': pages, 'page_type': page_type, }, context_instance=RequestContext(request)) return HttpResponse(json.dumps(data), "application/json") if 'images' in request.GET: #pages = profile_user.get_loved_images() pages = Image.objects.filter( users_loved=profile_user).order_by('-imageloves__date') manage_perm = False data['html'] = render_to_string( 'images/images_loves.html', { 'image_rows': pages.get_rows(0, 4, row_size=3, order=False), 'profile_user': profile_user, 'total_rows': pages.total_rows(), 'photos_count': pages.count(), 'manage_perm': manage_perm, 'ajax': True, }, context_instance=RequestContext(request)) return HttpResponse(json.dumps(data), "application/json") if request.method == 'GET' and 'ajax' in request.GET: data['html'] = render_to_string( 'profile/loves_items.html', { 'items': pages, }, context_instance=RequestContext(request)) return HttpResponse(json.dumps(data), "application/json") pages = pages.filter(type='BS') #pages = list(chain(pages, posts)) #pages = sorted(pages, key=lambda item: PageLoves.objects.get(page=item, user=request.user).date if isinstance(item, Pages) else PostLoves.objects.get(post=item, user=request.user).date, reverse=True) return render_to_response( 'profile/loves.html', { 'profile_user': profile_user, 'current_user': profile_user, 'form_mess': form_mess, 'items': pages, 'loves_view': True, }, 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 test_valid_form(self): r = Message.objects.create(send_to=self.user1, sent_from=self.user2, subject="new message", message="a;ldkfasldfksadlfk") data = {'message': r.message, 'subject': r.subject} form = MessageForm(data=data) self.assertTrue(form.is_valid(), True)
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), )