def send_message(request, recipient): title = 'Send message' if timezone.now() >= request.user.date_joined + timezone.timedelta( minutes=10): permission = Permission.objects.get(name="Send Private Message") request.user.user_permissions.add(permission) if not request.user.has_perm('users.send_private_message'): wait_sec = (timezone.timedelta(minutes=10) - (timezone.now() - request.user.date_joined)).seconds messages.add_message( request, messages.WARNING, 'New users must wait 24 hours before they can send private messages.' '(So that you can test this feature you can send a private ' f'message in {wait_sec//60:0>2} min and {wait_sec%60:0>2} sec)') return redirect('index') user = get_object_or_404(User, username=recipient) if request.method == "POST": form = MessageForm(request.POST) if form.is_valid(): msg = Message(sender=request.user, recipient=user, body=form.cleaned_data['message']) msg.save() messages.add_message(request, messages.SUCCESS, 'Your message has been sent.') return redirect('index') else: form = MessageForm() return render(request, 'users/send_message.html', { 'title': title, 'form': form, 'recipient': recipient })
def post(self, request, chat_id): form = MessageForm(data=request.POST) if form.is_valid(): message = form.save(commit=False) message.chat_id = chat_id message.author = request.user message.save() url = '/dialogs/' + chat_id + '/' return HttpResponseRedirect(url) context = {'chat_id': chat_id} return render(request, 'users/messages.html', context=context)
def send_message(request): form = MessageForm(request.POST) # TODO: what happens if title in post data is longer than model field max_length? if not form.is_valid(): # TODO: show error messages u'Необходимо указать тему письма', u'Сообщение не должно быть пустым' return HttpResponse('Форма заполнена неверно') try: recipient_id = int(request.POST.get('id', '')) recipient = Profile.objects.select_related('user').get(id=recipient_id) except ValueError, Profile.DoesNotExist: return HttpResponse(u'Получатель указан неверно')
def send_message(modeladmin, request, queryset): form = None if 'cancel' in request.POST: modeladmin.message_user(request, 'The action is canceled') return HttpResponseRedirect(request.get_full_path()) elif 'send' in request.POST: form = MessageForm(request.POST) if form.is_valid(): receiver_list = [] for user in queryset: if hasattr(user, 'email'): if user.email is not None and user.email != '': receiver_list.append(user.email) if hasattr(user, 'user'): if user.user.email is not None and user.user.email != '': receiver_list.append(user.user.email) subject, from_email, to = form.cleaned_data.get( 'subject'), '*****@*****.**', receiver_list text_content = 'This is an important message.' html_content = form.cleaned_data.get('message') msg = EmailMultiAlternatives(subject, text_content, from_email, to) msg.attach_alternative(html_content, "text/html") msg.send() if len(receiver_list) == 1: modeladmin.message_user( request, _(f"Mail sent successfully for selected {modeladmin.model._meta.verbose_name.title()}" )) else: modeladmin.message_user( request, _(f"""Mail sent successfully for {len (receiver_list)} {modeladmin.model._meta.verbose_name_plural.title()}""" )) return HttpResponseRedirect(request.get_full_path()) if not form: form = MessageForm( initial={ '_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME), 'action': request.POST['action'] }) return render(request, 'admin/send_mass_mail.html', locals())
def send_message(request): """ 向某人发送信息 / 支持群发 """ if request.method != 'POST': form = MessageForm() else: form = MessageForm(request.POST, request.FILES) if form.is_valid(): tmp_message = form.save(commit=False) username_list = request.POST['receiver_id'] username_list = re.split(r'[\s\,\;]+', username_list) for username in username_list: if username.strip() == "": continue try: receiver_user = User.objects.get(username=username.strip()) except ObjectDoesNotExist: return render(request, 'users/userIsNotExist.html') Message.objects.create(text=tmp_message.text, receiver=receiver_user, sender=request.user) return HttpResponseRedirect(reverse('home:home')) info_id = UserInfo.objects.get(user=request.user).id context = {'form': form, 'info_id': info_id} return render(request, 'users/send_message.html', context)
def get(self, request, chat_id): try: chat = Chat.objects.get(id=chat_id) if request.user in chat.members.all(): chat.message_set.filter(is_readed=False).exclude( author=request.user).update(is_readed=True) else: chat = None except Chat.DoesNotExist: chat = None context = { 'user_profile': request.user, 'chat': chat, 'form': MessageForm(), } return render(request, 'users/messages.html', context)
def read_message(request, message_id): """ 阅读消息完整内容并回复 """ message = Message.objects.get(id=message_id) if request.user == message.receiver: message.is_read = True message.save() if request.method != 'POST': form = MessageForm() else: form = MessageForm(request.POST, request.FILES) if form.is_valid(): new_message = form.save(commit=False) new_message.receiver = message.sender new_message.sender = request.user new_message.save() return HttpResponseRedirect(reverse('users:notice')) context = {'message': message, 'form': form} return render(request, 'users/read_message.html', context)
def new_view(request): # Authentication check. authentication_result = views.authentication_check(request) if authentication_result is not None: return authentication_result # Get the template data from the session template_data = views.parse_session(request, {'form_button': "Send Message"}) if request.method == 'POST': form = MessageForm(request.POST) if form.is_valid(): message = Message( target=form.cleaned_data['target'], sender=request.user.account, header=form.cleaned_data['header'], body=form.cleaned_data['body'], ) message.save() logger.log(Action.ACTION_MESSAGE, 'Message sent', request.user) form = MessageForm() # Clean the form when the page is redisplayed template_data['alert_success'] = "Successfully sent your message!" else: form = MessageForm() template_data['form'] = form return render(request, 'page/message/new.html', template_data)
def leave_message(request, the_id=None): if request.method == 'GET': if the_id: try: the_id = int(the_id) except ValueError: raise Http404 else: raise Http404 rcpt = User.objects.filter(pk=the_id) if not rcpt: raise Http404 rcpt = rcpt[0] form = MessageForm() return render_to_response("users/leave_message.html", { 'user': request.user, 'rcpt': rcpt, 'form': form, }, context_instance=RequestContext(request)) elif request.method == 'POST': if request.POST.has_key('xhr'): r = HttpResponse(mimetype="text/xml") r.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") def fail(): r.write("<result><msg>failure</msg></result>") return r else: def fail(): raise Http404 if request.POST.has_key('rcpt'): try: rcpt = int(request.POST['rcpt']) except ValueError: return fail() rcpt = User.objects.filter(pk=rcpt) if not rcpt: return fail() rcpt = rcpt[0] else: return fail() form = MessageForm(request.POST) if form.is_valid(): form.save(request, rcpt) if request.user.attrs.has_key('sent_messages'): request.user.attrs['sent_messages'] += 1 else: request.user.attrs['sent_messages'] = 1 request.user.save() if rcpt.attrs.has_key('inbox'): rcpt.attrs['inbox'] += 1 else: rcpt.attrs['inbox'] = 1 rcpt.save() if request.POST.has_key('xhr'): r.write("<result><msg>success</msg></result>") return r return HttpResponseRedirect('/messages/sent/') if request.POST.has_key('xhr'): r.write("<result><msg>failure</msg></result>") return r return render_to_response("users/leave_message.html", { 'user': request.user, 'form': form, }, context_instance=RequestContext(request)) raise Http404