def view_message(request, pk): profile=request.user.get_profile() messages = Message.objects.filter(thread=pk) if ((messages[0].to == profile) or (messages[0].author == profile)): if request.POST: form = MessageForm(request.POST) if form.is_valid(): form.save(commit=False) f = form f.author = profile f.save() else: print form.errors message_list = Message.objects.filter(thread=pk).order_by('-date_created') message_form = MessageForm() return render_to_response('publication/message_thread.html', { 'message_list': message_list, 'message_form': message_form, 'profile':profile, }, context_instance=RequestContext(request)) else: return HttpResponseRedirect('/messages/')
def home(): # return "Hello, World!" # return a string error = None print current_user.id context = { 'title': "Login Page", 'creator': "Sahai Srichock", } #print "hello home" form = MessageForm(request.form) if form.validate_on_submit(): new_message = BlogPost( form.title.data, form.description.data, current_user.id ) db.session.add(new_message) db.session.commit() flash('New entry was successfully posted. Thank.') return redirect(url_for('homes.home')) #return render_template( #'index.html', posts=posts, error=error, form=form, context=context) else: posts = db.session.query(BlogPost).all() return render_template( 'index.html', posts=posts, error=error, form=form, context=context) # render a template
def view_message(request, pk): profile = request.user.get_profile() messages = Message.objects.filter(thread=pk) if (messages[0].to == profile) or (messages[0].author == profile): if request.POST: form = MessageForm(request.POST) if form.is_valid(): form.save(commit=False) f = form f.author = profile f.save() else: print form.errors message_list = Message.objects.filter(thread=pk).order_by("-date_created") message_form = MessageForm() return render_to_response( "publication/message_thread.html", {"message_list": message_list, "message_form": message_form, "profile": profile}, context_instance=RequestContext(request), ) else: return HttpResponseRedirect("/messages/")
def create_message(request, recipient_id=None): """ Create a new message """ if request.method == 'POST': form = MessageForm(request.POST, request.FILES, user=request.user) if form.is_valid(): message = form.save(commit=False) message.author = request.user message.sent_at = datetime.now() message.save() for ban in message.recipient.get_profile().is_banned(): ban.end_time = datetime.now() ban.save() return redirect(reverse("private_messages_inbox")) else: if recipient_id: user = User.objects.get(pk=recipient_id) form = MessageForm(user=request.user, initial={'recipient': user}) else: form = MessageForm(user=request.user) return render_to_response("private_messages/message_new.html", {"form": form}, context_instance=RequestContext(request))
def group_info(request, group_id): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): msg = form.cleaned_data['message'] message = GroupMessage() message.group_id = group_id message.from_email = request.user.username message.message = msg message.save() # send signal grpmsg_added.send(sender=GroupMessage, group_id=group_id, from_email=request.user.username) # Always return an HttpResponseRedirect after successfully dealing # with POST data. return HttpResponseRedirect(reverse('group_info', args=[group_id])) else: form = MessageForm() op = request.GET.get('op', '') if op == 'delete': return group_remove(request, group_id) elif op == 'dismiss': return group_dismiss(request, group_id) elif op == 'quit': return group_quit(request, group_id) return render_group_info(request, group_id, form)
def home(): """Renders the home page.""" form = MessageForm(request.form) if request.method == 'POST' and form.validate(): #Save to db table_service = TableService(account_name=config.ACC_NAME, account_key=config.ACC_KEY) message = {'PartitionKey': 'message', 'RowKey': form.name.data + datetime.datetime.now().isoformat(), 'name' : form.name.data, 'email': form.email.data, 'date' : str(datetime.datetime.now())} if form.message_body.data: message["message"] = form.message_body.data table_service.insert_entity('landingmessages', message) return render_template( 'index.html', hiden_block='#wright-us', form=form, ) return render_template( 'index.html', hiden_block='#got-ur-message', form=form, )
def logged_in(request, username): user = get_object_or_404(User, username=username) if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): Message.objects.create( user=user, msg=form.cleaned_data['msg'], ) return HttpResponseRedirect('?') else: form = MessageForm() # Use SQL to get the Message objects out via JOIN and DISTINCT msgs = Message.objects.filter( Q(user=user) | Q(user__following__dst=user) ).distinct() # Alternatively, use .as_model() to get the User objects out msgs = Tree('messages-for-%s' % user).values().as_model(Message) return render_to_response('logged_in.html', { 'user': user, 'form': form, 'msgs': Paginator(msgs, 10).page(request.GET.get('page', 1)), }, context_instance=RequestContext(request))
def post(self): user_id = force_int(self.get_argument('user_id', 0), 0) current_user = self.current_user user = User.get(id=user_id) if user: form = MessageForm(self.request.arguments) if form.validate(): message_box1 = current_user.get_message_box(user=user) message_box2 = user.get_message_box(user=current_user) if not message_box1: message_box1 = MessageBox(sender_id=current_user.id, receiver_id=user.id, status=1).save() if not message_box2: message_box2 = MessageBox(sender_id=user.id, receiver_id=current_user.id).save() message = form.save(user_id=current_user.id, message_box1_id=message_box1.id, message_box2_id=message_box2.id) result = {"status": "success", "message": "私信发送成功", "content": message.content, "created": message.created, "avatar": current_user.get_avatar(size=48), "url": current_user.url, "id": message.id} else: result = {"status": "error", "message": "请填写至少 4 字的内容"} if self.is_ajax: return self.write(result) self.flash_message(result) return self.redirect_next_url() result = {"status": "error", "message": "没有目标用户,不能发送私信哦"} if self.is_ajax: return self.write(result) self.flash_message(result) return self.redirect_next_url()
def submit(request): """ returns a message submission page processes a message submission """ # Process message form if it has been submitted if request.method == 'POST': message_form = MessageForm(request.POST) recipient_form = RecipientForm(request.POST) attachment_form = AttachmentForm(request.POST, request.FILES) # Enter into database and email users if valid if (message_form.is_valid() and recipient_form.is_valid() and attachment_form.is_valid()): message = message_form.save() attachment_form.save(message) recipient_form.save(message) return render_to_response('thanks.html') # If message has not submitted, render message form else: message_form = MessageForm() recipient_form = RecipientForm() attachment_form = AttachmentForm() return render(request, "submit.html", { "formset": message_form, "recipients": recipient_form, "attachments": attachment_form })
def moderation_object(request, message_id): messages = [] message = get_object_or_404(Message, id=message_id, point__isnull=False) if not message.point.location.admins.filter(id=request.user.id).count(): return HttpResponseNotFound() form = None if request.method == "POST": if message.app.uid != 'webclient': mform = MessageForm(request.POST, instance=message) else: mform = None if message.point: form = BasePointForm(request.POST, instance=message.point, prefix="point") else: if message.app.uid != 'webclient': mform = MessageForm(instance=message) else: mform = None if message.point: form = BasePointForm(instance=message.point, prefix="point") if request.method == "POST": if all([mform is None or mform.is_valid(), form.is_valid()]): if mform is not None: mform.save() form.save() messages.append(u'Изменения успешно сохранены') return render_to_response('manager_moderation_obj.html', {'obj': message, 'info': {'messages': messages}, 'mform': mform, 'form': form }, RequestContext(request))
def reply(request, topic): if request.method == "POST": message_form = MessageForm(request.POST, instance=Message()) topic = Topic.objects.get(slug=topic) if message_form.is_valid(): message = message_form.save(commit=False) message.category = topic.forum.category message.topic = topic message.forum = topic.forum message.user = request.user message.save() action.send(request.user, verb='replied to', target=message.topic) message.topic.responded_to = datetime.datetime.now() message.topic.save() Topic.objects.filter(id=topic.id).update(reply_count=F('reply_count')+1) return HttpResponseRedirect(reverse('djero.views.topic', kwargs={ 'category' : topic.forum.category.slug, 'forum' : topic.forum.slug, 'topic' : topic.slug })) else: return HttpResponse("Invalid") else: message_form = MessageForm() topic = get_object_or_404(Topic, slug=topic) return render(request, "forum/reply.html", { "message_form" : message_form, "topic" : topic, })
def message(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] content = form.cleaned_data['content'] ip = request.META['REMOTE_ADDR'] sess = request.session if not sess.has_key( 'name' ) or sess['name'] != name: sess['name'] = name if name.lower() == 'orange': name = 'Wrong way' content = 'Try to pwn a shell instead of cracking md5.' elif md5.new(name).hexdigest() == 'e5bc16fcbca0f279df17b66d8c37e109': name = 'Orange' Messages( name=name, content=content, ip=ip ).save() return HttpResponseRedirect( '/' ) else: sess = request.session.load() if sess.has_key( 'name' ): default = sess['name'] else: default = 'Guest' form = MessageForm( initial={'name': default} ) messages = Messages.objects.order_by('id').reverse()[:100] response = render_to_response( 'message.html', {'form': form, 'messages': messages} ) return response
def post(self): user_id = force_int(self.get_argument('user_id', 0), 0) sender = self.current_user receiver = User.get(id=user_id) if receiver: form = MessageForm(self.request.arguments) if form.validate(): message = form.save(sender_id=sender.id, receiver_id=receiver.id) result = { "status": "success", "message": "私信发送成功", "content": message.content, "created": message.created, "avatar": sender.get_avatar(size=48), "url": sender.url, "id": message.id, } else: result = {"status": "error", "message": "请填写至少 4 字的内容"} self.send_result(result) self.finish() return WebSocketHandler.send_message(message.receiver_id, message) result = {"status": "error", "message": "没有目标用户,不能发送私信哦"} self.send_result(result)
def msq_query(request, id): c = {} group_info = get_group(request.session['token'], id) c['member_map'] = {member[u'user_id']: member[u'nickname'] for member in group_info[u'members']} form = MessageForm(request.GET, created=group_info['created_at'], members=c['member_map']) if form.is_valid(): d = form.cleaned_data c['messages'] = Message.objects.filter(group=id, created__lte=d['end_date'], created__gte=d['start_date'], n_likes__gte=d['min_likes'], n_likes__lte=d['max_likes'], author__in=d['sent_by'], text__icontains=d['text_contains']) if d['text_not_contain']: c['messages'] = c['messages'].exclude(text__icontains=d['text_not_contain']) if d['img']: c['messages'] = c['messages'].exclude(img__isnull=True) if d['random']: c['messages'] = list(c['messages']) random.shuffle(c['messages']) c['messages'] = c['messages'][:int(d['limit'])] else: sort = '-' + d['sort_by'] if d['sort_order'] else d['sort_by'] sort = (sort, '-created') if d['sort_by'] == 'n_likes' else (sort, '-n_likes') c['messages'] = c['messages'].order_by(sort[0], sort[1])[:int(d['limit'])] return render(request, 'message_table.html', c) else: return HttpResponse("");
def message_create(request): if request.method == "POST": form = MessageForm(request.POST) if form.is_valid(): # TODO: content_object msg = Message(msg=form.cleaned_data["msg"], user=request.user) msg.save() return HttpResponseRedirect("/")
def busi_cooper_page(request): if request.method == 'POST': msgform = MessageForm(request.POST); if msgform.is_valid(): ctrls.saveMessageByForm(request,msgform); return HttpResponseRedirect("/busi_cooper/") else: return render_to_response('businesscooper.html',context_instance=RequestContext(request))
def post(self): abort_if_not_an_admin() data = ImmutableMultiDict(request.json) message_form = MessageForm(data, csrf_enabled=False) if message_form.validate(): message_form.save() return {"status": "success"} return message_form.errors
def messaging_compose(request, response_format='html'): "New message page" user = request.user.profile if request.POST: if 'cancel' not in request.POST: message = Message() message.author = user.get_contact() if not message.author: return user_denied(request, message="You can't send message without a Contact Card assigned to you.", response_format=response_format) form = MessageForm( request.user.profile, None, None, request.POST, instance=message) if form.is_valid(): message = form.save() message.recipients.add(user.get_contact()) message.set_user_from_request(request) message.read_by.add(user) try: # if email entered create contact and add to recipients if 'multicomplete_recipients' in request.POST and request.POST['multicomplete_recipients']: try: conf = ModuleSetting.get_for_module( 'anaf.messaging', 'default_contact_type')[0] default_contact_type = ContactType.objects.get( pk=long(conf.value)) except Exception: default_contact_type = None emails = request.POST[ 'multicomplete_recipients'].split(',') for email in emails: emailstr = unicode(email).strip() if re.match('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr): contact, created = Contact.get_or_create_by_email( emailstr, contact_type=default_contact_type) message.recipients.add(contact) if created: contact.set_user_from_request(request) except: pass # send email to all recipients message.send_email() return HttpResponseRedirect(reverse('messaging')) else: return HttpResponseRedirect(reverse('messaging')) else: form = MessageForm(request.user.profile, None) context = _get_default_context(request) context.update({'form': form}) return render_to_response('messaging/message_compose', context, context_instance=RequestContext(request), response_format=response_format)
def send(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): send_message(from_user=request.user, form=form) return redirect('/message/sended') else: form = MessageForm() return render_to_response('message/send.html', {'form': form}, context_instance=RequestContext(request))
def message(request, event_id, type): event = get_object_or_404(Event, id=event_id) form = MessageForm(user=request.user, event=event, type=type, data=(request.POST or None), initial={"guests": request.GET.get("guests", "").split(",")}) if form.is_valid(): form.save() messages.success(request, "Your message has been sent.") return redirect(event) template = "events/message.html" return render_to_response(template, locals(), context_instance=RequestContext(request))
def sendmessage(request): basic = get_basic(request) message_sent = False try: user = User.objects.get(id=request.GET['id']) except User.DoesNotExist: return HttpResponseRedirect('/messages') if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.from_user = request.user obj.to_user = user obj.save() try: to_prof = Profile.objects.get(user=user) except Profile.DoesNotExist: to_prof = Profile() if to_prof.message_email: try: from_prof = Profile.objects.get(user=request.user) except Profile.DoesNotExist: from_prof = Profile() if from_prof.first_name: from_name = from_prof.first_name if from_prof.last_name: from_name = " ".join([from_name, from_prof.last_name]) else: from_name = request.user.username if to_prof.first_name: to_name = to_prof.first_name else: to_name = user.username title = "CreationDex - New Message from " + from_name msg_url = "https://creationdex.com/viewmessage?id=" + str(obj.id) from_url = "https://creationdex.com/profile?id=" + str(request.user.id) options_url = "https://creationdex.com/accounts/options/" plain_content = ("Hello, " + to_name + ".\n\n" + from_name + " has sent you a new message. Go to " + msg_url + " to read it" + " at creationdex.com, or go to " + options_url + " to change" + " your email options.\n\n Preview: \"" + obj.content + "\"") html_content = ("<p>Hello, " + to_name + ".</p><p><a href=\"" + from_url + "\">" + from_name + "</a>" + " has sent you a new message. Click <a href=\"" + msg_url + "\">here</a>" + " to read it at creationdex.com, or click" + " <a href=\"" + options_url + "\">here</a> to change your" + " email options.</p>" + "<p>Preview: \"" + obj.content + "\"</p>") send_mail(title, plain_content, settings.EMAIL_HOST_USER, [user.email], fail_silently=True, html_message=html_content) return HttpResponseRedirect('/messages/') else: form = MessageForm() return render(request, 'sendmessage.html', {'form': form, 'basic': basic, 'user': user })
def post_message(request, event_id): if request.method == "POST": form = MessageForm(request.POST) if form.is_valid(): event = get_object_or_404(Event, pk=event_id) message = form.cleaned_data['message'] user = request.user message_obj = Message.objects.create(event=event, datetime=datetime.now(), user=user, message=message) return HttpResponseRedirect(reverse("view_event", args=[event_id])) else: return HttpResponse(form.errors)
def contact_form_process(request): contact_form_done = False message_form = MessageForm(request.POST or None, prefix="message") if message_form.is_valid(): obj = message_form.save() d = {"text": obj.text, "name": obj.name, "phone": obj.phone, "email": obj.email, "subject": obj.subject, } Email.objects.get(id_name="message").send(settings.NOTIFY_MAIL, d, obj.email) contact_form_done = True message_form = None # return HttpResponseRedirect("/") return contact_form_done, message_form
def send_message(request): if request.method != 'POST': return HttpResponseNotFound() form = MessageForm(request.POST) other_user = form['recip'] if form.is_valid(): cd = form.cleaned_data m = Message(sender=request.user, recip=cd['recip'], subject=cd['subject'], content=cd['content'], thread_id=cd['thread_id']) m.save() return HttpResponseRedirect(reverse('inbox')) return HttpResponse('There was an error with your message')
def home(): error = None form = MessageForm(request.form) if form.validate_on_submit(): new_message = BlogPost(form.title.data, form.description.data, current_user.id) db.session.add(new_message) db.session.commit() flash("New entry was successfully posted. Thanks.") return redirect(url_for('home.home')) else: posts = db.session.query(BlogPost).all() return render_template('index.html', posts=posts, form=form, error=error)
def add_message(request, page_number=1): messages = Message.objects.filter(date_published__lte=timezone.now()).order_by('-date_published') current_page = Paginator(messages, 5) form = MessageForm(request.POST or None) if request.user.is_authenticated(): if form.is_valid(): message = form.save(commit=False) message.mes_user=request.user message.date_published=datetime.datetime.now() message.save() return redirect("/") return render_to_response('message.html', {'form': form, 'messages': current_page.page(page_number), 'username': auth.get_user(request).username}, RequestContext(request))
def new_message(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): newMessage = Message() save_message_from_form(newMessage, form) return HttpResponseRedirect('/sms/messages') else: form = MessageForm() return render_to_response('sms/new_message.html', {'form': form }, context_instance=RequestContext(request))
def save_message(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): newMessage = Message.objects.get(pk=form.cleaned_data['id']) save_message_from_form(newMessage, form) return HttpResponseRedirect('/sms/messages') else: form = MessageForm() return render_to_response('sms/edit_message.html', {'form': form }, context_instance=RequestContext(request))
def new_blogpost(author_id): error = None form = MessageForm(request.form) if form.validate_on_submit(): newpost = BlogPost(title=form.title.data, description=form.description.data, author_id=current_user.id) db.session.add(newpost) db.session.commit() flash('your post was successful', 'success') return redirect(url_for('blog')) return render_template('create-post.html', form=form, error=error)
def message_detail(id): # login.logout_user() try: message = Message.objects.filter(id = id) except Exception as e: print " exception value: ", e return redirect(url_for('.index')) form = MessageForm() form.content = message[0].message form.name_to = message[0].user.first_name form.name_from = message[0].user_from.first_name form.subject = message[0].subject return render_template('forum/message_detail.html',form=form)
def messages_add(): """Add a message: Show form if GET. If valid, update message and redirect to user page. """ if not g.user: flash("Access unauthorized.", "danger") return redirect("/") form = MessageForm() if form.validate_on_submit(): msg = Message(text=form.text.data) g.user.messages.append(msg) db.session.commit() return redirect(f"/users/{g.user.id}") return render_template('messages/new.html', form=form)
def messages_add(): """Add a message: Show form if GET. If valid, update message and redirect to user page. """ if not g.user: flash("You must be logged in to access this page.", "danger") return redirect("/") form = MessageForm() if form.validate_on_submit(): msg = Message(text=form.text.data) g.user.messages.append(msg) db.session.commit() return redirect("/") return render_template('messages/new.html', form=form)
def add_user_to_g(): """If we're logged in, add curr user to Flask global.""" if CURR_USER_KEY in session: g.user = User.query.get(session[CURR_USER_KEY]) g.logout_form = LogoutForm() g.like_form = LikeForm() g.liked_messages = set(g.user.liked_messages) g.message_form = MessageForm() else: g.user = None
def group_chat(id_=None): form = MessageForm() if request.method == 'POST': content = form.data.content send2 = form.data.send2 send2user = User.get_or_404(id=send2) message = Message(create_by=current_user.id, content=content, send2=send2) message.save() msgs = Message.objects(send2=id_) return render_template('/group_chat.html', msgs=msgs, form=form)
def chat(request, username): """Chat page.""" try: # adressee. do not allow user to chat with himself. user = User.objects.get(pk__ne=request.user.pk, username=username) except (DoesNotExist, MultipleObjectsReturned): raise Http404 all_messages = Message.objects.filter( Q(author=request.user, addressee=user) | Q(author=user, addressee=request.user)).order_by("created") # Mark unread messages as read. all_messages.filter(author=user, read=False).update(set__read=True) if request.method == "POST": form = MessageForm(request.POST) if form.is_valid(): message = form.save(commit=False) message.author = request.user message.addressee = user message.save() return redirect("chat", user.username) else: form = MessageForm() return render(request, 'chat.html', { "addressee": user, "form": form, "all_messages": all_messages })
def post(self): user_id = force_int(self.get_argument('user_id', 0), 0) current_user = self.current_user user = User.get(id=user_id) if user: form = MessageForm(self.request.arguments) if form.validate(): message_box1 = current_user.get_message_box(user=user) message_box2 = user.get_message_box(user=current_user) if not message_box1: message_box1 = MessageBox(sender_id=current_user.id, receiver_id=user.id, status=1).save() if not message_box2: message_box2 = MessageBox( sender_id=user.id, receiver_id=current_user.id).save() message = form.save(user_id=current_user.id, message_box1_id=message_box1.id, message_box2_id=message_box2.id) result = { "status": "success", "message": "私信发送成功", "content": message.content, "created": message.created, "avatar": current_user.get_avatar(size=48), "url": current_user.url, "id": message.id } else: result = {"status": "error", "message": "请填写至少 4 字的内容"} if self.is_ajax: return self.write(result) self.flash_message(result) return self.redirect_next_url() result = {"status": "error", "message": "没有目标用户,不能发送私信哦"} if self.is_ajax: return self.write(result) self.flash_message(result) return self.redirect_next_url()
def users_followers(user_id): """Show list of followers of this user.""" form = MessageForm() if not g.user: flash("Access unauthorized.", "danger") return redirect("/") user = User.query.get_or_404(user_id) all_likes = Likes.query.filter(Likes.user_id == user.id).all() return render_template('users/followers.html', user=user, form=form, count=len(all_likes))
def send_message(): form = MessageForm(request.form) if request.method == "POST": username = session["username"] recipient = User.query.filter(User.name == form.recipient.data).first() sender = User.query.filter(User.name == username).first() message = Message(message=form.message.data, sender=sender, recipient=recipient) db_commit(message) return redirect(url_for("messages", username=username)) else: return render_template("send_message.html", form=form)
def messages_add(): """Add a message: Show form if GET. If valid, update message and redirect to user page. """ if not g.user: flash("Access unauthorized.", "danger") return redirect("/home") form = MessageForm() if form.validate_on_submit(): msg = Message(text=form.text.data, ticker=form.ticker.data.upper(), title=form.title.data) g.user.posts.append(msg) db.session.commit() return redirect("/home") return render_template('messages/new.html', form=form, user=g.user)
def send_message(request): if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): cd = form.cleaned_data statement = 'Pomyślnie wysłano wiadomość.' form.save() return render(request, 'contact/success.html', {'statement': statement}) else: form = MessageForm() return render(request, 'contact/contact.html', {'form': form})
def post_message(request): if request.method == 'POST': form = MessageForm(request.POST, request.FILES) print request.POST if form.is_valid(): form.save() print "save ok" return HttpResponseRedirect('/success/') else: form = MessageForm() return render_to_response('messages/upload.html', {'form': form})
def emotion_post(): msg = request.form['message'] response = unirest.post( "https://community-sentiment.p.mashape.com/text/", headers={ "X-Mashape-Key": "6VWQcE5umumsh9oLsHfFlOseFGbDp1caaUKjsnj6PJRqxZKslv", "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" }, params={"txt": msg}) return render_template("my_form.html", mood=response.body['result']['sentiment'], form=MessageForm())
def home(): error = None form = MessageForm(request.form) if form.validate_on_submit(): new_message = BlogPost(form.title.data, form.description.data, current_user.id) db.session.add(new_message) db.session.commit() flash('New entry was successfully posted. Thanks.') return redirect(url_for('home.home')) else: posts = "" try: posts = db.session.query(BlogPost).all() except OperationalError: flash( "You have no database! Please, contact your system administrator to set up the database!" ) return render_template('index.html', posts=posts, form=form, error=error)
def sessions(team_id, sport): team = Teams.query.get_or_404(team_id) if current_user.phone in team.members: username = current_user.name formpage = MessageForm() if request.method == 'GET': formpage.username.data = current_user.name else: flash('Your not part of the team, you can not get into the chat!!') return redirect(url_for(sport)) return render_template('session.html', title='Team Chat', formpage=formpage, username=username)
def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) ## Update the intial view with the previous messages ## messages = self.request.session.get('messages', []) channels = self.request.session.get('channels', ['test_channel']) self.request.session['messages'] = messages self.request.session['channels'] = channels ## Send the form and initial messages in the context ## context['messages'] = self.request.session['messages'] context['form'] = MessageForm(initial={'subscribe_channels': channels}) return context
def chatting(user_id): global present_user print(present_user) user = User.query.get_or_404(user_id) form = MessageForm() if form.validate_on_submit(): print('hi') msg = Messages(form.message.data, present_user.name, user.name) db.session.add(msg) db.session.commit() db.session.refresh(msg) # form.submit.data = False return render_template('chatting.html', user=user, users=User.query.all(), messages=Messages.query.all(), form=form) print('data : ' + str(form.submit.data)) return render_template('chatting.html', user=user, users=User.query.all(), messages=Messages.query.all(), form=form)
def list_users(): """Page with listing of users. Can take a 'q' param in querystring to search by that username. """ form = MessageForm() search = request.args.get('q') if not search: users = User.query.all() else: users = User.query.filter(User.username.like(f"%{search}%")).all() return render_template('users/index.html', users=users, form=form)
def index(): form = MessageForm() image_sources = os.listdir('static/json_data/') image_sources = ['static/json_data/' + x for x in image_sources] image_data = [] for json_file in image_sources: with open(json_file) as json_: data = json.load(json_) print(data['static_link']) image_data.append(data) random.shuffle(image_data) if form.validate_on_submit(): contact = form.number.data blurb = "Welcome to Doggit! Please send pictures to this number for submission. You may optionally include a caption!" print(contact) print("click") message = client.messages.create(to=contact, from_="+13143100209", body=blurb) return redirect('/index') return render_template('index.html', form=form, image_sources=image_data)
def direct_messages(other_user_id): """ Shows conversation with other user """ form = MessageForm() msgs = DirectMessage.query.filter( or_((and_(DirectMessage.user_to_id == g.user.id, DirectMessage.user_from_id == other_user_id)), (and_(DirectMessage.user_to_id == other_user_id, DirectMessage.user_from_id == g.user.id)))).order_by( DirectMessage.timestamp.desc()).all() if form.validate_on_submit(): new_dm = g.user.send_dm(other_user=other_user_id, msg=form.text.data) db.session.commit() route = request.referrer return redirect(f'{route}') return render_template("direct_messages/show_dm.html", messages=msgs, form=form, user=g.user)
def mess_send(*args,**kwargs): form = MessageForm(request.form) if request.method == 'POST' and 'proj_id' in kwargs and form.validate(): mess = Messages(content = form.message.data, kind = 'project', author = g.user, project = Projects.query.get(kwargs['proj_id']), reciever = Projects.query.get(kwargs['proj_id']).user ) db.session.add(mess) db.session.commit() flash('Message send') return redirect('/projects/%s#/2' % kwargs['proj_id']) if request.method == 'POST' and 'author' in kwargs and form.validate(): mess = Messages(content = form.message.data, kind = 'private', author = g.user, reciever = User.query.filter_by(name = kwargs['author']).first() ) db.session.add(mess) db.session.commit() flash('Message send') return redirect('/user/%s#/2' % g.user.name) return redirect('.')
def message(): form = MessageForm(request.form) choices = [] users = db.session.query(User).all() for user in users: select = user.agency + " - " + user.last + ", " + user.first choice = (user.email, select) choices.append(choice) form.users.choices = choices if form.validate_on_submit(): recipients_type = form.recipients.data print db.session.query(User.email).all() if (recipients_type == 'Users'): recipients = request.form.getlist('users') elif (recipients_type == 'Agencies'): recipients = db.session.query( User.email).filter(User.agency == recipients).all() elif recipients_type == 'All Users': recipients = db.session.query(User.email).all() subject = form.subject.data message = form.message.data #msg = Message(subject=subject, body=message, sender=os.environ.get('DEFAULT_MAIL_SENDER'), recipients=recipients) #mail.send(msg) return render_template('message.html', form=form)
def messages_add(): """Add a message: Show form if GET. If valid, update message and redirect to user page. """ if not g.user: flash("Access unauthorized.", "danger") return redirect("/") form = MessageForm() if form.validate_on_submit(): # the next line works, but it shouldn't due to nullable=False. Why? # msg = Message(text=form.text.data) msg = Message(text=form.text.data, user_id=g.user.id) g.user.messages.append(msg) db.session.commit() return redirect(f"/users/{g.user.id}") return render_template('messages/new.html', form=form)
def message(parking_id): form = MessageForm(request.form) user = current_user # Get the information related to this parking spot parking_spot = Parking_Spot.get_parking_spot_by_id(parking_id) if request.method == 'POST': message = Message(user.uid, parking_spot.ownerid, parking_spot.psid, form.message.data) db.session.add(message) db.session.commit() return redirect(url_for('profile')) return render_template('message.html', parking_spot=parking_spot, form=form)
def message_detail(id): # login.logout_user() try: message = Message.objects.filter(id=id) except Exception as e: print " exception value: ", e return redirect(url_for('.index')) form = MessageForm() form.content = message[0].message form.name_to = message[0].user.first_name form.name_from = message[0].user_from.first_name form.subject = message[0].subject return render_template('forum/message_detail.html', form=form)
def mlist_view(request, mlist_id, response_format='html'): "Mailing List view page" user = request.user.profile mlist = get_object_or_404(MailingList, pk=mlist_id) if not request.user.profile.has_permission(mlist): return user_denied( request, message="You don't have access to this Mailing List", response_format=response_format) if request.user.profile.has_permission(mlist, mode='x'): if request.POST: message = Message() message.author = request.user.profile.get_contact() if not message.author: return user_denied( request, message= "You can't send message without a Contact Card assigned to you.", response_format=response_format) form = MessageForm(request.user.profile, mlist_id, None, request.POST, instance=message) if form.is_valid(): message = form.save() message.set_user_from_request(request) message.read_by.add(user) return HttpResponseRedirect( reverse('messaging_mlist_view', args=[mlist.id])) else: form = MessageForm(request.user.profile, mlist_id) else: form = None messages = Object.filter_by_request( request, Message.objects.filter(reply_to__isnull=True, mlist=mlist).order_by('-date_created')) context = _get_default_context(request) context.update({'messages': messages, 'form': form, 'mlist': mlist}) return render_to_response('messaging/mlist_view', context, context_instance=RequestContext(request), response_format=response_format)
def users_show(user_id): """Show user profile.""" form = MessageForm() user = User.query.get_or_404(user_id) # snagging messages in order from the database; # user.messages won't be in order by default messages = ( Message.query # .filter(Message.user_id == user_id) .order_by(Message.timestamp.desc()).limit(100).all()) #getting all likes to be counted for like-count all_likes = Likes.query.filter(Likes.user_id == user.id).all() return render_template('users/show.html', user=user, messages=messages, count=len(all_likes), form=form)
def homepage(): """Show homepage: - anon users: no messages - logged in: 100 most recent messages of followed_users """ if g.user: form = MessageForm() following = [u.id for u in g.user.following] messages = (Message .query .filter((Message.user_id.in_(following)) | (Message.user_id == g.user.id)) .order_by(Message.timestamp.desc()) .limit(100) .all()) likes = [like.id for like in g.user.likes] return render_template('home.html', messages=messages, likes=likes, form=form) else: return render_template('home-anon.html')
def homepage(): """Show homepage: - anon users: no messages - logged in: 100 most recent messages of followed_users """ form = MessageForm() if g.user: likes = g.user.likes following = g.user.following f_id = [ff.id for ff in following] f_id.append(g.user.id) messages = (Message.query.filter(Message.user_id.in_(f_id)).order_by( Message.timestamp.desc()).limit(100).all()) return render_template('home.html', messages=messages, likes=likes, form=form) else: return render_template('home-anon.html')
def dm(friend_id): user_id = current_user.id messages = [] friend = db.select_user(friend_id)[0] first_name = friend[0] last_name = friend[1] full_name = first_name + ' ' + last_name messages_list = db.select_messages(current_user.id, friend_id) for message in messages_list: if message[0] == friend_id: indiv = { 'first_name': first_name, 'message': message[2] } messages.append(indiv) else: indiv = { 'first_name': current_user.first_name, 'message': message[2] } messages.append(indiv) messages.reverse form = MessageForm() return render_template('dm.html', receiver_id = friend_id, name = full_name, messages=messages, form=form, title='Direct Messages')
def project_index(proj_id): form = CommentForm(request.form) mess = MessageForm(request.form) proj = db.session.query(Projects).filter_by(id=proj_id).first() if proj is None: abort(404) css=True if g.user in proj.get_users(): css=False if request.method == 'POST' and form.validate(): comm = Comments(form.comment.data, g.user, proj) db.session.add(comm) db.session.commit() flash('Comment added') #td change anchor in v0.9 return redirect('projects/%s#2' % proj_id) #app.logger.debug(proj.get_users()) return render_template('project.html', query=proj, form=form, mess=mess, css=css)