예제 #1
0
def index(request,idm=None):
    nbrepost = 20
    try :
        conf = Configuration.objects.get(id__exact=1)
        nbrepost = conf.NbreMessage
    except :
        pass

    
    if request.method == 'POST':
        form = MessageForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            pseudo = form.cleaned_data['Pseudo']
            description = form.cleaned_data['Description']
            message = form.cleaned_data['Message']
            post = Message.objects.create(Description=description,Pseudo=pseudo,Message=message)
            post.save()
    if request.method == 'GET':
        if request.GET.get('idm'):
            idm = int(request.GET['idm'])
            print idm
    form = MessageForm() # An unbound form
    total = Message.objects.count()
    if idm == None or idm > total or idm < nbrepost :
        idm = total
    j = total + 444
    i = total
    while i < j :
        i = i +1
        post =  Message.objects.create(Description=i,Pseudo=i,Message=i)
        post.save()
    listemessage = Message.objects.filter(id__range=(idm-nbrepost+1,idm)).order_by('-id')
    supp = nbrepost + idm +1
    minus =  idm - nbrepost -1
    return render_to_response('index.html', {'form': form,'listemessage':listemessage,'idm':idm,'nbrepost':nbrepost,'total':total,'supp':supp,'minus':minus},RequestContext(request))
예제 #2
0
    def test_empty_form(self):
        """
        Tests that an empty form is invalid.
        """
        empty_form = MessageForm(self.user1)

        self.assertFalse(empty_form.is_valid())
예제 #3
0
def message(request):

    sent = False

    if request.method == "POST":
        contact_form = MessageForm(data=request.POST)

        if contact_form.is_valid():
            message = contact_form.save()

            subject = "PVSAT Enquiry from %s %s" % (message.first_name, message.last_name)

            text_content = render_to_string("message_temp.txt", {"message": message})

            msg = EmailMultiAlternatives(subject, text_content, "", [settings.DEFAULT_FROM_EMAIL])

            if settings.EMAIL_STATUS:
                msg.send()

            # send_mail(request.POST['subject'], request.POST['message'], '', [settings.ADMIN_EMAIL], fail_silently=False)
            sent = True
        else:
            print contact_form.errors
    else:
        contact_form = MessageForm()

    return render(request, "message.html", {"contact_form": contact_form, "sent": sent})
예제 #4
0
def home(request):
    """render contact form

    if a form is submitted check if it is valid and save it
    """
    ci = RequestContext(request)
    tmpl = {}
    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            message = Message(
                    name=form.cleaned_data['name'],
                    mail=form.cleaned_data['mail'],
                    message=form.cleaned_data['message']
                )
            message.save()
            tmpl['form'] = MessageForm()
            tmpl['success'] = 1
        else:
            tmpl['form'] = form
            tmpl['error'] = 1
    else:
        form = MessageForm()
        tmpl['form'] = form
    return render_to_response("message/home.html", tmpl, ci)
예제 #5
0
    def test_different_sharezone_form(self):
        """
        Tests that forms sending a message to users in different ShareZones are
        invalid.
        """
        address = Address.objects.create(address_line_1="43 Life St.",
                                         address_line_2='',
                                         city="Rochester",
                                         state="NY",
                                         zip_code="14623")

        djuser = DJUser.objects.create_user("mickey", "*****@*****.**", "password")
        different_sharezone_user = User.objects.create(django_user=djuser, address=address)

        sharezone2 = Sharezone.objects.create(name="University of Rochester", 
                                              description="Another University in Rochester")
        sharezone2.admin.add(djuser)

        sharer = Sharer.objects.get(pk=different_sharezone_user.id)
        sharer.sharezone = sharezone2
        sharer.save()

        different_sharezone1 = {"to_username": "******", "message": \
                                "I shouldn't be able to send a message to you :("}
        different_sharezone1_form = MessageForm(different_sharezone_user, 
                                                different_sharezone1)

        different_sharezone2 = {"to_username": "******", "message": \
                                "I shouldn't be able to send a message to you :("}
        different_sharezone2_form = MessageForm(self.user1, different_sharezone2)

        self.assertFalse(different_sharezone2_form.is_valid())
        self.assertFalse(different_sharezone1_form.is_valid())
예제 #6
0
파일: views.py 프로젝트: randomp/wishList
def send_message(request):
    if request.method == 'POST':
        m = MessageForm(request.POST)
        if m.is_valid():
            new_message = m.save()
            return HttpResponseRedirect('/contact.html')
    return render_to_response('contact.html', RequestContext(request))
예제 #7
0
def create(request, project_id):
    project = get_object_or_404(
        Project,
        id=project_id,
        is_active=True,
        author__is_active=True
    )
    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            message = Message(
                author=request.user,
                project=project,
                text=form.cleaned_data['text']
            )
            message.save()
            return redirect(
                request,
                'project-message_list',
                [project.id],
                {request.url_name: 'True'}
            )
    else:
        form = MessageForm()
    params = {'project': project, 'form': form}
    params.update(csrf(request))
    return response(request, params)
 def send_message(self, request):
     form = MessageForm(request.POST)
     if form.is_valid():
         message = form.save()
         CentrifugeClient.publish(message)
         serializer = self.get_serializer(message, many=False)
         return Response(serializer.data)
     return JsonResponse({'errors': form.errors}, status=400)
예제 #9
0
    def test_to_yourself_form(self):
        """
        Tests that forms sending a message to yourself are invalid.
        """
        to_yourself = {"to_username": "******", "message": "Hi me!"}
        to_yourself_form = MessageForm(self.user1, to_yourself)

        self.assertFalse(to_yourself_form.is_valid())
예제 #10
0
    def test_valid_form(self):
        """
        Tests that a form with a specified username and message is valid.
        """
        content = {"to_username": "******", "message": "Hello World!"}

        valid_form = MessageForm(self.user1, content)

        self.assertTrue(valid_form.is_valid())
예제 #11
0
    def test_userDNE_form(self):
        """
        Tests that forms sending a message to a user that does not exist are
        invalid.
        """
        user_DNE = {"to_username": "******", "message": "dskljdapwjpi"}
        user_DNE_form = MessageForm(self.user1, user_DNE)

        self.assertFalse(user_DNE_form.is_valid())
예제 #12
0
파일: views.py 프로젝트: Axiodis/chirp
def new_chirp(request):
    if request.method == "POST":
        form = MessageForm(request.POST, request.FILES or None)
        if form.is_valid():
            chirp = form.save(commit=False)
            chirp.user_id = request.user.id
            chirp.save()
        else:
            messages.error(request, form.errors)
    return redirect(request.META.get('HTTP_REFERER'))
예제 #13
0
파일: views.py 프로젝트: Nuskaiym/catalog
def send_message(request, *args, **kwargs):
    message_form = MessageForm(data=request.POST)
    if message_form.is_valid():
        print('postko keldi')
        new_message = message_form.save(commit=False)
        new_message.save()
        return HttpResponseRedirect('/')
    else:
        print('no valid!!!!!!!!!!!')
    return HttpResponse('invalid form')
예제 #14
0
    def test_missing_info_forms(self):
        """
        Tests that forms missing information (username or no message) are invalid.
        """
        no_username = {"message": "Bonjour!"}
        no_username_form = MessageForm(self.user1, no_username)

        no_message = {"to_username": "******"}
        no_message_form = MessageForm(self.user1, no_message)

        self.assertFalse(no_username_form.is_valid())
        self.assertFalse(no_message_form.is_valid())
def send_message(request):
    if "POST" == request.method:
        form = MessageForm(request.POST)
        if form.is_valid():
            message = form.save()
            CentrifugeClient.publish(message)
            return JsonResponse({
                'msg': 'Сообщение отправлено',
                'id': message.id,
            })
        return JsonResponse({'errors': form.errors}, status=400)
    return HttpResponseNotAllowed(['POST'])
예제 #16
0
def my_message(request):
    form = MessageForm()
    message_list = Message.objects.all().order_by('-created_time')
    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            form.save()
    form = MessageForm()
    return render(request, 'message/my_message.html', locals())
예제 #17
0
def add(request):

    if request.method == 'POST':
        form = MessageForm(request.POST)

        if form.is_valid():
            form.instance.author = request.user
            form.instance.ready_to_send = request.POST.get('ready_to_send', False)
            message = form.save()
            return HttpResponseRedirect('/message/view/%d' % message.id)

    else:
        form = MessageForm()

    return render_to_response('message/add.html', { 'form': form }, context_instance=RequestContext(request))
예제 #18
0
def message(request):

	submitted = False

	if request.method == 'POST':
		contact_form = MessageForm(data=request.POST)

		if contact_form.is_valid():
			message = contact_form.save()
			submitted = True

		else:
			print contact_form.errors
	else:
		contact_form = MessageForm()
	
        return render(request, 'message.html', {'contact_form': contact_form, 'submitted': submitted})
예제 #19
0
def edit(request, message_id):

    message = get_object_or_404(Message, id=message_id)

    if request.method == 'POST' and not message.sending_started:
        form = MessageForm(request.POST, instance=message)

        if form.is_valid():
            form.instance.author = request.user
            form.instance.ready_to_send = request.POST.get('ready_to_send', False)
            message = form.save()
            return HttpResponseRedirect('/message/view/%d/' % message.id)

    else:
        form = MessageForm(instance=message)

    return render_to_response('message/edit.html', { 'form': form, 'message': message }, context_instance=RequestContext(request))
예제 #20
0
def create_message(request):
    token = request.headers.get('Authorization')[6:]
    form = MessageForm(request.POST, request.FILES)
    if form.is_valid():
        # print(request.POST, request.FILES)
        data = request.POST
        my_id = Token.objects.filter(key=token).values('user_id')[0]['user_id']
        message = Message(chat_id=data['chat_id'], user_id=my_id, content=data['content'])
        session = boto3.Session()
        s3_client = session.client(service_name='s3',
                                   endpoint_url='http://hb.bizmrg.com',
                                   aws_access_key_id='ns3JMEzqS7GkxRcCuvRDVh',
                                   aws_secret_access_key='8DvkXKZkUdebaEkBfnyGKhJBZaMaW4ybJdxwiN2WzeEv')  
        if request.POST['attachment_type'] == 'null':
            print('without attachment')
            message.save()
            return JsonResponse({'Result':'Message created without attachment'})
        elif request.POST['attachment_type'] == 'images':
            print('with images')
            message.save()
            uploaded_file = request.FILES.getlist('media')
            for file in uploaded_file:
                print(file)
                url_location = 'attachments/chat' + data['chat_id'] + '/' + data['attachment_type'] + '/' + file.name + '-' + str(hash(file))
                s3_client.put_object(Bucket='z3hdro_messenger', Key=url_location, Body = file)
                attach = Attachment(chat_id=data['chat_id'], user_id=my_id, message_id=message.id, type_attachment=data['attachment_type'], url = url_location)
                attach.save()
            return JsonResponse({'Result':'Message created with image attachment'})
        elif request.POST['attachment_type'] == 'audio_message':
            print('with audio')
            message.save()
            uploaded_file = request.FILES['media']
            url_location = 'attachments/chat' + data['chat_id'] + '/' + data['attachment_type'] + '/' + 'audio-' + str(hash(uploaded_file))
            s3_client.put_object(Bucket='z3hdro_messenger', Key=url_location, Body = uploaded_file)
            attach = Attachment(chat_id=data['chat_id'], user_id=my_id, message_id=message.id, type_attachment=data['attachment_type'], url = url_location)
            attach.save()
            return JsonResponse({'Result':'Message created with audiorecord attachment'})
        elif request.POST['attachment_type'] == 'geolocation':
            print('with geolocation')
            message.save()
            attach = Attachment(chat_id=data['chat_id'], user_id=my_id, message_id=message.id, type_attachment=data['attachment_type'], url = data['geolocation_url'])
            attach.save()
            return JsonResponse({'Result':'Message created with geolocation'})
        return JsonResponse({'error':'unexpected bug'}, status=400)
    return JsonResponse({'error': form.errors}, status=400, json_dumps_params={'ensure_ascii': False})
예제 #21
0
def create_message(request, pk):
    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            m = Message(user=request.user,
                        char=Chat.objects.get(id=pk),
                        content=data['text'])
            m.save()
            text = "Сообщение отправлено"
        else:
            text = "Ошибка при обработке данных"
    else:
        text = "Ошибка при отправке сообщения"
    id = pk
    return render_to_response('message/textform.html', {
        'text': text,
        'id': id
    })
예제 #22
0
def ReplyMessage(request, mid):
    reply_to = Message.objects.get(pk=mid)
    if request.method == "POST":
        form = MessageForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            quoted_message = Message.objects.get(pk=mid)
            subject = data.get('subject')
            body = data.get('message')
            reply_message = Message(subject=subject, body=body)
            Inbox(request.user).reply_to_message(quoted_message=quoted_message,
                                                 reply_message=reply_message)
            messages.info(request, "Reply Sent", extra_tags="reply-confirm")
            return redirect('instructor:Inbox')
    else:
        form = MessageForm()

    context = {'MessageForm': form, 'mid': mid, 'reply_to': reply_to}
    return render(request, 'instructor/ReplyToMessage.html', context)
예제 #23
0
파일: views.py 프로젝트: KD233233/kd
def readerWall(request):
    about_list = About.objects.all()

    form = MessageForm()
    message_list = Message.objects.all()
    posts = Post.objects.all()
    context = contrl(request, posts)
    context['form'] = form
    context['message_list'] = message_list
    context['about_list'] = about_list
    return render(request, 'readerWall.html', context=context)
예제 #24
0
def add_msg(request):
    # A HTTP POST?
    if request.method == 'POST':
        form = MessageForm(request.POST)

        # Have we been provided with a valid form?
        if form.is_valid():
            human = True
            # Save the new category to the database.
            new_message = form.save(commit=True)

            # Now call the index() view.
            # The user will be shown the homepage.
            return show_msg(request, str(new_message.id))
#             return render(request, 'add.html', {
#                 'page_title': 'message delivered',
#             })
        else:
            # The supplied form contained errors - just print them to the terminal.
            print form.errors
    else:
        # If the request was not a POST, display the form to enter details.
        form = MessageForm()

    return render(request, 'add.html', {
        'page_title': 'Contact us',
        'form': form,
    })
예제 #25
0
def message(request):

    sent = False

    if request.method == 'POST':
        contact_form = MessageForm(data=request.POST)

        if contact_form.is_valid():
            message = contact_form.save()

            subject = 'PVSAT Enquiry from %s %s' % (message.first_name, message.last_name)

            text_content = render_to_string("message_temp.txt", {'message' : message})

            msg = EmailMultiAlternatives(subject, text_content, '', [settings.DEFAULT_FROM_EMAIL])

            if settings.EMAIL_STATUS:
                msg.send()

            #send_mail(request.POST['subject'], request.POST['message'], '', [settings.ADMIN_EMAIL], fail_silently=False)
            sent = True
        else:
            print contact_form.errors
    else:
        contact_form = MessageForm()

    return render(request, 'message.html', {'contact_form': contact_form, 'sent': sent})
예제 #26
0
파일: views.py 프로젝트: pianojet/fyfitness
def write(request, msg_id=None, mem_id=None):
	me = Member.objects.get(user=request.user)
	dbmessage=""
	if request.method == 'POST':
		form = MessageForm(request.POST)

		if form.is_valid():
			msg = form.save(commit=False)
			msg.from_member = me
			msg.save()
			send_mail('Find Your Fitness', 'Find Your Fitness: %s has sent you a message. \n"%s"\n\n  Click here to read it:  %s/message/browse/%s/ \n\n(please do not reply to this link)\n - Find Your Fitness'%(msg.from_member.user.username, msg.title, settings.ROOT_SITE_URL, msg.id), 'donotreply', ['%s'%(msg.to_member.user.email)], fail_silently=True)

			message = "Message sent."
			return render_to_response('public_site/home.html', {
			'message': message,
			'dbmessage': dbmessage,
			}, context_instance=RequestContext(request))
	else:
		if (msg_id and mem_id):
			msg_reply = Message.objects.get(id=msg_id)
			mem_reply = Member.objects.get(id=mem_id)
			form = MessageForm(initial={'title':"RE:%s"%(msg_reply.title), 'to_member':mem_reply.user})
		elif (mem_id):
			mem_reply = Member.objects.get(id=mem_id)
			form = MessageForm(initial={'to_member':mem_reply.user})
		else:
			form = MessageForm()
	
	
	return render_to_response('message/write.html', {
	'form': form,
	}, context_instance=RequestContext(request))
예제 #27
0
def message(request):
    error=False
    user=request.user
    if not user.is_authenticated():
        return redirect('/login')

    if request.method == 'POST':
        messageForm = MessageForm(data=request.POST)
        if messageForm.is_valid():

            userKey=messageForm.getUserKey()
            if userKey != 0:

                message = messageForm.save(commit=False)
                message.sender=user
                message.timeStamp=timezone.now()
                message.receiver=userKey
                message.save()

                log= Log()
                log.user = user
                log.username = request.user.username
                log.time = timezone.now()
                log.type = 'Message'
                log.save()
            else:
                error = True

    else:
        messageForm = MessageForm()

    #unread=Message.objects.filter(receiver=user, read=False)
    #unreadCount=len(unread)
    #unread.update(read=True)
    messages=Message.objects.filter(Q(receiver=user) | Q(sender=user)).order_by('-timeStamp')

    context= {'messageForm': messageForm, 'messages': messages, 'user': User,
              'error': error}
    return context
예제 #28
0
def message(request):
    submitted = False

    if request.method == 'POST':
        contact_form = MessageForm(data=request.POST)

        if contact_form.is_valid():
            submitted = True
            form = contact_form

            text_content = render_to_string("contact_text.txt", {'form': form})
            html_content = render_to_string("contact_html.html", {'form' : form} )
            msg = EmailMultiAlternatives(request.POST['subject'], text_content, '', ['*****@*****.**'])
            msg.attach_alternative(html_content, "text/html")
            msg.send()

        else:
            print contact_form.errors

    else:
        contact_form = MessageForm()

    return render(request, 'message.html', {'contact_form': contact_form, 'submitted': submitted})
예제 #29
0
def sendmessage(request):
    """
    Generates the view for sendmessage.html which displays a form for the User
    to send a message to another user. Upon submission, a Message object with
    the properties from_user, to_user, and message is created and stored in
    the database.
    """
    users = Sharer.objects.filter(sharezone=request.user.user.sharezone, _my_subclass='user'). \
                                  exclude(id=request.user.id)

    if request.method == 'POST':

        form = MessageForm(request.user.user, request.POST)

        if form.is_valid():
            from_user = request.user.user
            to_user = DJUser.objects.get(username=request.POST['to_username']).user
            message = form.cleaned_data['message']

            msg = Message.objects.create(from_user=from_user, to_user=to_user, 
                                         message=message, 
                                         sharezone=request.user.user.sharezone)

            form = MessageForm(request.user.user)
            context = {'success': True, 'form': form, 'users': users}

            return render(request, 'message/sendmessage.html', context)
        else:
            context = {'form': form, 'users': users}
            return render(request, 'message/sendmessage.html', context)

    form = MessageForm(request.user.user)

    context = {'form': form, 'users': users}

    return render(request, 'message/sendmessage.html', context)
예제 #30
0
파일: views.py 프로젝트: kitodan/travela
    def post(self, request, receiver, product_created=None, *args, **kwargs):
        if request.method == 'POST':
            form = MessageForm(request.POST, request.FILES)
            send_by = self.request.user
            send_to = (Trip.objects.filter(
                id=receiver).latest('date_posted')).posted_by
            if form.is_valid():
                form.instance.send_by = send_by
                form.instance.send_to = send_to
                form.save()
                return render(request, 'journey/home.html', {'form': form})

            else:
                form = MessageForm()
            return render(request, 'journey/about.html', {'form': form})
예제 #31
0
def user_detail(request, user_id):
    posts = InstagramUser.objects.all().filter(id=user_id)
    post = InstagramUser.objects.get(id=user_id)
    friend = InstagramUser.objects.get(id=user_id)
    photo = Photo.objects.all().filter(poster_id=user_id)
    form = MessageForm()
    follows = friend.friends.all()[1:]
    friends = friend.following.all()
    print(request.user.friends.all())
    return render(
        request, "user_detail.html", {
            'heading': 'Profile Page',
            'photo': photo,
            'posts': posts,
            'user_id': user_id,
            'form': form,
            'following': post.friends.count() - 1,
            'number': photo.count(),
            'follows': follows,
            'friends': friends
        })
예제 #32
0
def message(request):

	sent = False

	if request.method == 'POST':
		contact_form = MessageForm(data=request.POST)

		if contact_form.is_valid():
			message = contact_form.save()
			sent = True
			send_mail(request.POST['subject'], request.POST['message'], '*****@*****.**', ['*****@*****.**'], fail_silently=False)
		else:
			print contact_form.errors
	else:
		contact_form = MessageForm()
	
        return render(request, 'message.html', {'contact_form': contact_form, 'sent': sent})
def message_post(request, template='message/message_post.html', extra_context=None):
    is_send = False
    research = None
    message = None
    content_object_id = request.GET.get('content_object_id', None)
    recipient_id = request.GET.get('recipient_id', None)
    type = request.GET.get('type', None)
    message_id = request.REQUEST.get('message_id', None)

    if message_id and message_id != 'None':
        message = Message.objects.get(id=message_id)

    if request.method == 'POST':
        form = MessageForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            content_object_id = form.cleaned_data.get('content_object_id', None)
            recipient_id = form.cleaned_data.get('recipient_id', None)
            subject = form.cleaned_data.get('subject', None)
            content = form.cleaned_data.get('content', None)
            type = form.cleaned_data.get('type', None)
            send_email = form.cleaned_data.get('send_email', False)

            if message:
                message.subject = subject
                message.content = content
                message.send_email = send_email
                message.save()
                is_send = True
            else:
                recipient_id = recipient_id.split(',') if recipient_id else []
                recipient_list = User.objects.filter(id__in=recipient_id if recipient_id else [])
                if recipient_list and len(recipient_list) > 0:
                    if content_object_id:
                        research = Research.objects.get(id=content_object_id)

                    for recipient in recipient_list:
                        if type == TYPE_CANCEL_RESEARCH and not research.can_cancel():
                            continue
                        if type == TYPE_FEEDBACK:
                            messages = Message.objects.filter_message(content_object=research, recipient=recipient)
                            if messages and len(messages) > 0:
                                continue
                        Message.objects.create_message(content_object=research, subject=subject, content=content, type=type,
                                                       sender=request.user, recipient=recipient, send_email=send_email)
                    success(request, _(u'Message was successfully sent.'))
                    is_send = True
    else:
        if message:
            form = MessageForm(initial={
                'subject': message.subject,
                'content': message.content,
                'send_email': message.send_email,
                'content_object_id': message.content_object.id,
                'recipient_id': message.recipient.id,
                'type': message.type,
                'message_id': message.id,
            })
        else:
            form = MessageForm(initial={
                'content_object_id': content_object_id,
                'recipient_id': recipient_id,
                'type': int(type) if type else type,
                'message_id': message_id,
            })

    context = {
        'form': form,
        'is_send': is_send
    }

    if extra_context:
        context.update(extra_context)
    return render_to_response(template, context, context_instance=RequestContext(request))
예제 #34
0
def contact_tag():
    message_form = MessageForm()
    return {'message_form': message_form}
예제 #35
0
def new_chirp(request):
    if request.method == "POST":
        form = MessageForm(data=request.POST)
        if form.is_valid():
            form.save()
    return redirect("index")