예제 #1
0
파일: views.py 프로젝트: alexevseev/mysite
def show_about(request):
    if request.method == "POST":
        copyRequest = request.POST.copy()
        if request.user.is_authenticated():
            ## in case of user is logged in, username and email fields are not shown
            ## get username and email from database
            user = MyUser.objects.get(username = request.user)
            copyRequest['name'] = user.username
            copyRequest['email'] = user.email
        form = ContactForm(copyRequest)
        if form.is_valid():
            recipients = [settings.ADMINS[0][1], ]            
            name = form.cleaned_data['name']
            subject = "Mysite message from {0}".format(name)            
            message = form.cleaned_data['message']
            sender = form.cleaned_data['email']
            messages.success(request, "Сообщение отправлено")
            send_mail(subject, message, sender, recipients)
            return HttpResponseRedirect(reverse('thankyou_url')) # Redirect after POST
        else:
            pass
    else:
        form = ContactForm()    
    template_context =  {'form':form, 'my_age':get_my_age(),}
    return render_to_response('about/form.html', template_context, RequestContext(request))
예제 #2
0
def contact(request):
    
    mail_sent = None
    
    if request.method == 'POST':
        
        form = ContactForm(request.POST)
        if form.is_valid():
            url     = request.build_absolute_uri()
            name    = form.cleaned_data['name']
            email   = form.cleaned_data['email']
            phone   = form.cleaned_data['phone']
            subject = u'Contato de ' + name
            message = form.cleaned_data['message']
            message = u'Mensagem enviada por %s <%s> %s \n\n%s \n\n\nMensagem enviada através da página:\n%s' % (name, email, phone, message, url)
            
            try:
                mail_managers(subject, message, fail_silently = False)
                mail_sent = True
            except Exception as e:
                mail_sent = False
                if settings.DEBUG:
                    raise # reraises the exception
    else:
        form = ContactForm()
    
    template = loader.get_template('contact/contact.html')
    context = RequestContext(request, {
        'form'      : form,
        'mail_sent' : mail_sent,
    })
    return HttpResponse(template.render(context))
예제 #3
0
파일: app.py 프로젝트: andyzt/tceh
def home():

    storage = Storage()
    items_to_validate = storage.items

    if request.method == 'POST':
        form = ContactForm(request.form)
        if form.validate():
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=5,
                border=4,
            )
            qr.add_data(form.data['title'])
            qr.make(fit=True)
            img = qr.make_image()

            buff = StringIO.StringIO()
            img.save(buff, 'GIF')
            encoded_data = base64.b64encode(buff.getvalue())
            model = BlogPostModel(datetime.datetime.now(),form.data['title'],form.data['text'],encoded_data)
            items_to_validate.append(model)
    else:
        form = ContactForm()

    return render_template('home.html',
                           form=form,
                           items=items_to_validate,
                           )
예제 #4
0
파일: views.py 프로젝트: poohmeng/pooh_sae
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            subject=cd['subject']
            message=cd['message']
            from_email=cd.get('from_email', '*****@*****.**')
            sender=EMAIL_HOST_USER
            try:
                send_mail(subject,[from_email,message],sender,
                          ['*****@*****.**'], fail_silently=False)

                thread = Thread(target=send_mail,args=(subject,message,from_email,['*****@*****.**']))
                thread.start()
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return HttpResponseRedirect('/poohApp/thanks/')

    else:
        form = ContactForm(
            initial = {'subject':'I love this one!'}
        )
    c = {}
    c = RequestContext(request, {
        'form':form,
        })
    return render_to_response('contact/contact.html',c)
예제 #5
0
파일: app.py 프로젝트: LBConsulting/mrna
def contact_form():
    form = ContactForm(request.form)
    msg = {}
    if request.method == 'POST' and form.validate():
        if form.nospam.data == '2':
            if form.message.data != "8":
                print "WARN: bot attempted usage on contact form!"
                warned = warn_admin(request, mail)
                if warned['succ_code'] != 0:
                    print "there was an error emailing the report"
                abort(403)
            subject = form.subject.data
            message = form.emessage.data
            sender = form.sender.data
            msg = dict(sender=sender, subject=subject, message=message)
            ##_log_mail(msg)
            ret = mail_admin(msg, mail)
            if ret['succ_code'] != 0:
                flash("There was an error sending this message")
                return redirect(url_for('contact_success'))
            else:
                flash("Message: %(subject)s was sent successfully by %(email)s" %\
                        {
                            "subject" : msg['subject'],
                            "email" : msg['sender'],
                        })
                print "successfully sent to SMTP"
                return redirect(url_for('contact_success'))
    return render_template('base.html', msg=msg, form=form)
예제 #6
0
파일: views.py 프로젝트: 18dubu/MMS-NEW
def contact(request):
    if request.method == 'POST':
	form = ContactForm(request.POST)
        if form.is_valid():
            
	  	fromemail = form.cleaned_data['from_email']
		header = form.cleaned_data['subject']
		to =  DEFAULT_ADMIN_EMAIL_LIST
		content = form.cleaned_data['content']
		msg = EmailMultiAlternatives(header, content, fromemail, to)
		msg.content_subtype = "html"
		msg.send()

		return HttpResponseRedirect('/virtual/confirm/?h=success&t=Email Sent!&c=We will try to come back to you ASAP! &b1=main&b2=console')
    else:

	if request.user.is_authenticated():
		init_data = {'from_email':request.user.email}
                form = ContactForm(initial=init_data)
	else:
        	form = ContactForm()

    args = {}
    args.update(csrf(request))
    args['contactform'] = form
    args['user'] = request.user

    return render_to_response('contact_form.html', args)
예제 #7
0
파일: views.py 프로젝트: jayquest/higiprag
def contato(request):
    sucesso = False

    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass

            contato = Contato()

            contato.nome = form.cleaned_data['nome']
            contato.email = form.cleaned_data['email']
            contato.assunto = form.cleaned_data['assunto']
            contato.mensagem = form.cleaned_data['mensagem']

            contato.save()

            sucesso = True


    else:
        form = ContactForm() # An unbound form

    try:
        texto_contato = TextoContato.objects.get(slug='texto_contato')
    except:
        texto_contato = None

    try:
        configs_contato = ConfiguracoesContato.objects.get(slug='configs_contato')
    except:
        configs_contato = None

    return render_to_response('contact.html',{'form':form,'current':'contato','sucesso':sucesso,'texto_contato':texto_contato,'configs_contato':configs_contato},context_instance=RequestContext(request))
예제 #8
0
def send(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)

        if form.is_valid():
            msg = Message()
            msg.username = form.cleaned_data['username']
            msg.email = form.cleaned_data['email']
            msg.phone = form.cleaned_data['phone']
            msg.location = form.cleaned_data['location']
            msg.job = form.cleaned_data['job']
            msg.description = form.cleaned_data['description']
            msg.area = form.cleaned_data['area']

            try:
                msg.save()
                mail_managers('ZUBIRD webpage - new message received', 'Otrzymałeś nową wiadomość.')
            except Exception as e:
                import traceback
                logger.error(str(e))
                logger.error(traceback.format_exc())
                return render_to_response('error.html', {})
            
            return render_to_response('thanks.html', {})
        else:
            return render_to_response('base.html', Context({'form':form}))
    else:
        return index(request)    
예제 #9
0
파일: views.py 프로젝트: cgsv/djangoSite
def contact(request):
    form = ContactForm()
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('thanks/')
    return render(request, 'contact.html', {'form': form})
예제 #10
0
def makeorder(request):
    order=OrderRequest(request)
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            try:
                cd = form.cleaned_data
                cd["decoration_id"] = order.decorationId
                if cd["DecorationIngredient"]:
                    cd["decoration_ingredient_name"] = DecorationIngredient.objects.get(pk=cd["DecorationIngredient"]).title_ru
                utils.send_order_email(cd)
                return HttpResponseRedirect(reverse("mail_sent_confirmation"))
                print "Mail sent"
            except Exception as ex:
                form._errors["__all__"] = form.error_class([str(ex)])
                print "Error in mail sending!!!"

        else:
            print "data is not valid", form.errors
    else:
        form = ContactForm()

    data = {"order": order, "form": form, "decoration_ingredients": DecorationIngredient.objects.all()}

    response=render_to_response("makeorder.html", data, context_instance=RequestContext(request, processors=[base_proc]))
    #order.save(response)
    return response
예제 #11
0
def main_list(request):
    peer_list = Peer.objects.all()
    if request.method == 'POST':
        c_form = ContactForm(request.POST)
        if c_form.is_valid():
            peer = c_form.save(commit=False)
            peer.user = request.user
            peer.save()          
    else:
        c_form = ContactForm()

    if 'q' in request.GET and request.GET['q']:
        q = request.GET['q']
        people = Peer.objects.filter(name__icontains=q)
        return render(request, 'peer-search-block.html', {
            'peer_list': peer_list, 
            'c_form': c_form,
            'people': people,
            'query': q
        })

    return render(request, 'peer-list-block.html', {
        'peer_list': peer_list, 
        'c_form': c_form,
    })
예제 #12
0
파일: views.py 프로젝트: dnarda/mandir
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)

        if form.is_valid():
            form.save()
            contact = form.instance

            mandir_staff = getattr(settings, "MANDIR_STAFF", None)

            ## Send Thank you email
            message = "Dear " + contact.name + "\n"
            message += "Thank you for your message. We will get back to you soon!"
            send_mail("Thank you from Ved Mandir!", message, '*****@*****.**', [contact.email])

            ## Notify Ved mandir staff
            message = "New Contact message received from: " + contact.name + "\n"
            message += "Subject: " + contact.subject + "\n"
            message += "Message: \n"
            message += contact.message  + "\n"
            message += "-----------------------------------------------------\n"
            send_mail("New Contact Message", message, '*****@*****.**', mandir_staff)

            return render(request, 'ved/contact.html', {} )
        else:
            return render(request, 'ved/contact.html', {'form':form} )
            
    else:
        form = ContactForm()
        return render(request, 'ved/contact.html', {'form':form} )
예제 #13
0
def contact(request):
	if request.method == 'POST':
		form = ContactForm(request.POST)
		if form.is_valid():

			subject   = form.cleaned_data['subject']
			message   = form.cleaned_data['message']
			sender    = form.cleaned_data['sender']
			cc_myself = form.cleaned_data['cc_myself']

			recipients = ['*****@*****.**']
			if cc_myself:
				recipients.append(sender)

			# as confs de e-mail no settings.py sao ficticias
			# por isso send_mail esta comentada
			# send_mail(subject, message, sender, recipients)

			return HttpResponseRedirect('/thanks')
	else:
		form = ContactForm()


	return render_to_response('contact.html', {
		'form': form,
		}, context_instance=RequestContext(request))
예제 #14
0
def contact(request):

    test_expression, answer = produce_expression()
    request.session['last_answer'] = request.session.get('answer', None)
    request.session['answer'] = answer

    #answer = request.session['answer']
    if request.method == 'POST':  # If the form has been submitted...
        # form = ContactForm(request.POST) # A form bound to the POST data
        # A form bound to the POST data
        form = ContactForm(request.POST, request=request)
        if form.is_valid():  # All validation rules pass
            cd = form.cleaned_data
            recipients = ['*****@*****.**']
            if cd['cc_myself']:
                recipients.append(cd['sender'])

            send_mail(cd['subject'], cd['message'], '*****@*****.**',
                      recipients, fail_silently=False)

            # Process the data in form.cleaned_data
            # Redirect after POST
            return HttpResponseRedirect(reverse('index'))
            # return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm()  # An unbound form

    c = {'subtitle': 'Contact Us', 'form': form, 'test': test_expression}
    c.update(csrf(request))
    return render_to_response('blog_app/contact_form.html', c)
예제 #15
0
def contact():
    contact_form = ContactForm()
    if request.method == 'POST':
        if contact_form.validate_on_submit():
            human_name = contact_form.name.data
            human_email = contact_form.email.data
            if human_name:
                sender_str = '({name}, {email})'.format(name=human_name, email=human_email)
            else:
                sender_str = '({email})'.format(email=human_email)
            subject_line = 'Pubs Warehouse User Comments'  # this is want Remedy filters on to determine if an email
            # goes to the pubs support group
            message_body = contact_form.message.data
            message_content = EMAIL_RESPONSE.format(contact_str=sender_str, message_body=message_body)
            msg = Message(subject=subject_line,
                          sender=(human_name, human_email),
                          reply_to=('PUBSV2_NO_REPLY', '*****@*****.**'),
                          # this is not what Remedy filters on to determine if a message
                          # goes to the pubs support group...
                          recipients=contact_recipients,
                          # will go to [email protected] if application has DEBUG = False
                          body=message_content)
            mail.send(msg)
            return redirect(url_for(
                'pubswh.contact_confirmation'))  # redirect to a conf page after successful validation and message sending
        else:
            return render_template('pubswh/contact.html',
                                   contact_form=contact_form)  # redisplay the form with errors if validation fails
    elif request.method == 'GET':
        return render_template('pubswh/contact.html', contact_form=contact_form)
예제 #16
0
def email(request):
    contact_flatpage = get_object_or_404(FlatPage, url='/help/contacts/')
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            code = 'CONTACT_FORM'
            ctx = form.cleaned_data
            try:
                event_type = CommunicationEventType.objects.get(code=code)
            except CommunicationEventType.DoesNotExist:
                # No event-type in database, attempt to find templates for this
                # type and render them immediately to get the messages.  Since we
                # have not CommunicationEventType to link to, we can't create a
                # CommunicationEvent instance.
                templates = CommunicationEventType.objects.get_and_render(code, ctx)
                event_type = None
            else:
                templates = event_type.get_messages(ctx)
            Dispatcher().dispatch_direct_messages(CONTACT_FORM_BCC, templates)
            messages.success(request, 'Ваше сообщение успешно отрпавлено')
    else:
        form = ContactForm()
    return render(request, 'flatpages/default.html', {
        "form": form,
        "flatpage": contact_flatpage,
        })
예제 #17
0
def result():
    if request.method == 'GET':
        form =  ContactForm(request.args)
        if form.validate():
            query = []
            if form.email:
                query.append(('email', form.email.data))
            if form.phone:
                query.append(('phone', form.phone.data.replace('+','')))
            if form.twitter:
                query.append(('twitter', form.twitter.data))
            if form.facebook:
                query.append(('facebookUsername', form.facebook.data))
            userdata = aggregate_data(query)
            return render_template('results/get_results.html', ud=userdata)
    elif request.method == 'POST':
        if request.files.get('file'):
            # get emails from file, if one was uploaded
            batch_data = emails_from_file(request.files.get('file'))
        else:
            batch_data = request.form.get('batch_data')
            if batch_data:
                batch_data = batch_data.replace('facebook', 'facebookUsername').split(',')
                for i in range(len(batch_data)):
                    batch_data[i] = tuple(batch_data[i].split(':'))
        if batch_data:
            response = batch_lookup(batch_data, request.url_root + url_for('webhook')[1:])
        else:
            response = ["Nothing to process"]
        return render_template('results/post_results.html', response=response)
예제 #18
0
파일: views.py 프로젝트: jtheoof/jjbrothers
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            if check_contact_form(request, cd): # This is spam
                m = _(u"Erreur lors de l'envoi réessayer ultérieurement.")
                messages.add_message(request, messages.ERROR, m)
            else:
                for m in [
                    _(u'Merci de nous avoir contactés.'),
                    _(u'Nous vous répondrons très rapidement.'),]:
                    messages.add_message(request, messages.INFO, m)
                message = '%s\r\n' % cd['message']
                message += 'From:  %s\r\n' % cd['sender']
                message += 'Email: %s\r\n' % cd['email']
                send_mail(
                    cd['subject'].encode("utf-8"),
                    message.encode("utf-8"),
                    settings.SERVER_EMAIL,
                    ['*****@*****.**', '*****@*****.**'])
            return HttpResponseRedirect('/contact')
        else:
            messages.add_message(request, messages.ERROR, 'Formulaire invalide.')
    else:
        form = ContactForm(label_suffix='')

    context = {
        'body_class': 'about',
        'form': form
    }
    return render_to_response(
        'web/contact.html',
        context,
        context_instance=RequestContext(request))
예제 #19
0
파일: views.py 프로젝트: deecewan/based
def create():
    form = ContactForm()
    if form.validate_on_submit():
        new_contact = Contact()
        new_name = Name()
        new_contact.email = form.email.data
        new_name.first_name = form.first_name.data
        new_name.last_name = form.last_name.data
        new_contact.name = new_name
        new_contact.group = form.group.data
        new_contact.known_from = form.known_from.data
        new_contact.general_comment = form.general_note.data
        new_contact.current_status = form.status.data
        for language in form.languages.data:
            if language:
                new_contact.tags.append(language)
        other_tags = form.other_tags.data.replace(', ', ',').split(',')
        for tag in other_tags:
            new_contact.tags.append(tag)
        try:
            new_contact.save()
            flash_string = '<a href=\"/{}\">{} {}</a> was added to the database.'
            flash_string = flash_string.format(new_contact.email, new_contact.name.first_name,
                                               new_contact.name.last_name)
            flash(Markup(flash_string))
            update_p_dict()
            return redirect(url_for('index'))
        except NotUniqueError:
            msg = "That email address is already in use.  <a href=\"/" + form.email.data + "\">View Entry.</a>"
            form.email.errors.append(Markup(msg))
        except Exception as e:
            flash("There were database-raised errors in the form.  Specifically, " + e.message)

    return render_template('create_contact.html', form=form)
예제 #20
0
파일: views.py 프로젝트: urg3n/dj
def contact(request):
    title='Contact Us'
    form = ContactForm(request.POST or None)
    if form.is_valid():
        form_email=form.cleaned_data.get("email")
        form_message = form.cleaned_data.get("message")
        form_full_name = form.cleaned_data.get("full_name")
        subject = 'Visitor Message'
        from_email = settings.EMAIL_HOST_USER
        to_email = [form_email, '*****@*****.**']   #email is sent to form_email and [email protected]
        contact_message = "fullname is %s  message : %s  email : %s" % (
        form_full_name,
        form_message,
        form_email
        )
        send_mail(subject,
              contact_message,
              from_email,
              to_email,
              fail_silently=False)

    context = {
       "form": form,
        "title": title,
    }
    return render(request, "forms.html", context)
예제 #21
0
파일: views.py 프로젝트: denigma/denigma
def contact(request):
    errors = []
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            try:
                send_mail(
                    cd['subject'],
                    cd['message'] + " Send by " + cd['email'],
                    cd.get('email', '*****@*****.**'), #'*****@*****.**'),
                    ['*****@*****.**'],                #['*****@*****.**'],
                )
            except:
                 # Because of the verfication problem with SES.
                 send_mail(
                    cd['subject'],
                    cd['message'] + " Send by " + cd['email'],
                    cd.get('mail', '*****@*****.**'),
                    ['*****@*****.**'],
                 )

            messages.add_message(request, messages.SUCCESS,
                ugettext("The enquiry has been sent."))
            #return HttpResponseRedirect('/contact/thanks') # thanks/
            return render_to_response('contact/thanks.html', context_instance=RequestContext(request))

    else:
        form = ContactForm(
            initial={'subject':'For the singularity!'})
    return render_to_response('contact/form.html', {'form':form}, context_instance=RequestContext(request))
예제 #22
0
def create():
    form = ContactForm()
    if form.validate() is False:
        for error_type in form.errors:
            if form.errors[error_type][0] in dictionary():
                form.errors[error_type][0] = dictionary()[form.errors[error_type][0]]
        return render_template('contact/index.html', form=form, action=url_for('contact.create'))
    else:
        contact = Form()
        contact.name = form.name.data
        contact.email = form.email.data
        contact.subject = form.subject.data
        contact.message = form.message.data
        contact.postage_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        message_tpl = render_template('contact/message_template.html', contact=contact)

        db.session.add(contact)
        db.session.commit()
        send_mail("Contato - DataViva", [admin_email], message_tpl)

        message = gettext("Your message has been sent successfully. We will soon get back to you.")
        flash(message, 'success')

        return redirect(url_for('contact.create'))
예제 #23
0
def contact(request):
    if request.method == 'POST':
        c={}
        form = ContactForm(request.POST)
        if form.is_valid():
            feedback = Feedback()
            try:
                feedback.name = form.cleaned_data["con_name"]
                feedback.email = form.cleaned_data["con_emailid"]
                try:
                    feedback.mobile = str(form.cleaned_data["con_mobile"])
                except:
                    feedback.mobile = ""
                #if feedback.mobile is None:
                #    feedback.mobile = 0
                feedback.value = form.cleaned_data["con_text"]
                feedback.save()
                c.update({"success":True})
            except:
                print sys.exc_info()[1]
                return HttpResponse('Error in sending feedback'+str(vars(feedback))+str(sys.exc_info()[0]))
            
            c.update(csrf(request))
            return render_to_response('contact.html',c)
        else:
            c={}
            c.update({"form":form})
            c.update(csrf(request))
            return render_to_response('contact.html',c)
    c={}
    c.update(csrf(request))
    return render_to_response('contact.html',c)
예제 #24
0
def contactanos(request, razon_contacto):
    template = "contactanos.html",

    if request.method == "POST":

        form = ContactForm(request.POST)

        if form.is_valid():
            tema = form.cleaned_data['tema']
            mensaje = form.cleaned_data['mensaje']
            correo = form.cleaned_data['correo']
            nombre = form.cleaned_data['nombre']

            enviar_mail_contactanos(nombre, correo, tema, mensaje)

            return redirect('perfiles:despues_contacto', razon_contacto=razon_contacto, correo_contacto=correo)

    else:

        if razon_contacto == "registrar_biblioteca":

            form = ContactForm(initial={'tema': "Registrar nueva Biblioteca Compartida"})
            form.fields['mensaje'].placeholder = "Hola, deseo registrar una Biblioteca Compartida ..."

        elif razon_contacto == "donacion":

            form = ContactForm(initial={'tema': "Hacer una donación de libros"})
            form.fields[
                'mensaje'].placeholder = "Hola, deseo donar mis libros, quiero que alguien más pueda leerlos ..."

        else:
            form = ContactForm()

    context = {'form': form, 'razon_contacto': razon_contacto}
    return render(request, template, context)
예제 #25
0
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        form.send()
        flash('Thanks for contacting us! We promise to get back to you soon.', 'contact')
        return redirect(url_for('contact'))
    return render_template('contact.html', title='Contact Us', form=form)
예제 #26
0
def contact(request):
    # errors = []
    if request.method == "POST":
        # if not request.POST.get('subject', ''):
        #        errors.append('Enter a subject.')
        # if not request.POST.get('message', ''):
        #        errors.append('Enter a message.')
        # if request.POST.get('email') and '@' not in request.POST['email']:
        #        errors.append('Enter a valid e-mail address.')
        # if not errors:
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            s = smtplib.SMTP("smtp.gmail.com", "25")
            s.ehlo()
            s.starttls()
            s.login("*****@*****.**", "su123456")
            send_mail(
                cd["subject"], cd["message"], cd.get("email", "*****@*****.**"), ["*****@*****.**"]
            )
            s.quit()
            return HttpResponseRedirect("/accounts/contact/thanks/")
    else:
        form = ContactForm(initial={"subject": "I love this one!"})
    c = RequestContext(request, {"form": form})
    return render_to_response("contact/contact_form.html", context_instance=c)
예제 #27
0
파일: views.py 프로젝트: Docworld/resume
def contact(request):
    
    errors = []
    if request.method == 'POST':
        form = ContactForm(request.POST)
        
        if form.is_valid():
            cd = form.cleaned_data
            email_message = cd.get('email', 'No email') + u'\n' + cd.get('subject', 'no subject') + u'\n' + cd.get('message','No message')
            
            db = email_list(
                email = cd.get('email', 'No email'),
                content = email_message
            )
            db.save()
            
            send_mail(
                cd['subject'],
                email_message,
                '*****@*****.**',
                ['*****@*****.**'],
                fail_silently=True,
            )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm(initial={'subject':u'网站还可以哦'})
    return render_to_response('contact_form.html', {'form': form})
예제 #28
0
    def dispatch_request(self):
        form = ContactForm()

        if request.method == "POST":
            if form.validate() is False:
                return render_template("contact/contact.html", form=form)
            else:
                msg = Message(
                    form.subject.data, sender=(form.name.data, form.email.data), recipients=["*****@*****.**"]
                )
                msg.html = """
		<b>De:</b> %s <i>%s</i>
		<h4><b>Mensaje:</b></h4>
		<p>%s</p>
		""" % (
                    form.name.data,
                    form.email.data,
                    form.message.data,
                )
                msg.body = """
		De: %s <%s>
		Mensaje:
		%s
		""" % (
                    form.name.data,
                    form.email.data,
                    form.message.data,
                )
                mail.send(msg)
                return render_template("contact/contact.html", success=True)

        elif request.method == "GET":
            return render_template("contact/contact.html", form=form)
예제 #29
0
파일: views.py 프로젝트: IlTorre/Aste
def contatti (request):
    """
    Visualizza il form di contatto in caso di get mentre in caso di post invia la mail.
    :param request: la richiesta
    :return: il render del template corretto a seconda dell'operazione
    """
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) #form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            subject = form.cleaned_data['oggetto']
            message = form.cleaned_data['messaggio']
            sender = form.cleaned_data['email']
            cc_myself = form.cleaned_data['invia_una_copia_a_me_stesso']
            recipients = ['*****@*****.**']
            message=message+'\n\nModulo inviato da: '+sender
            if cc_myself:
                recipients.append(sender)
	    send_mail(subject, message, sender, recipients)
            context={'titolo':'Messaggio inviato','corpo':"La tua richiesta e' stata registrata."}
            return render(request,'GestioneUtenti/avviso.html',context) # Redirect after POST
        else:
	    return render(request,'AsteOnLine/contatti.html',{ 'form': form, 'messaggio':'Compila i campi obbligatori' })
    else:  # GET request: just visualize the form
        form = ContactForm() # An unbound form
        return render(request, 'AsteOnLine/contatti.html', { 'form': form })
예제 #30
0
파일: flaskapp.py 프로젝트: flrs/tagespoet
def mainsite():
    """This function renders the main website.

    The function evaluates the contact form and gets poem data for both current and archive display from a database
    when loading the site.
    """

    # define standard display
    contact_form = ContactForm()
    contact_form_success = False
    jump_to_contact = False

    if request.method == 'POST':
        if not contact_form.validate():
            # contact form validation failed
            jump_to_contact = True
        else:
            # contact form validation succeeded, send email
            msg = Message('Neue Nachricht von Tagespoet.de!', sender=app.config['MAIL_USERNAME'],
                          recipients=[app.config['MAIL_RECIPIENT']])
            msg.body = """
            Von: %s <%s>
            %s
            """ % (contact_form.name.data, contact_form.email.data, contact_form.message.data)
            mail.send(msg)
            contact_form_success = True
            jump_to_contact = True

    # get poem of the day
    cur_poem = mongo.db.poems.find_one({}, sort=[('date', flask_pymongo.DESCENDING)])
    if cur_poem is not None:
        # poem found
        cur_poem_ret = make_poem_html(cur_poem['poem'], 'poemline')
        cur_poem_render_ret = 1
    else:
        # no poem found, return empty values
        # TODO: Implement error handling (logging, sending out maintenance request email)
        cur_poem_ret = ''
        cur_poem_render_ret = 0

    # organize archive
    first_poem = mongo.db.poems.find_one({}, sort=[('date', flask_pymongo.ASCENDING)])

    now = datetime.now()
    yesterdays_date = datetime(now.year, now.month, now.day, 0, 0, 1) + timedelta(hours=6) - timedelta(days=1)
    last_poem = mongo.db.poems.find_one({'date': {'$lte': yesterdays_date}}, sort=[('date', flask_pymongo.DESCENDING)])

    todays_date = datetime.today() + timedelta(hours=6)

    return render_template('index.htm', todays_date=todays_date.strftime("%d.%m.%YYYY"),
                           cur_poem_render=cur_poem_render_ret,
                           cur_poem=cur_poem_ret,
                           first_poem_date=first_poem['date'].strftime('%d.%m.%Y'),
                           last_poem_date=last_poem['date'].strftime('%d.%m.%Y'),
                           last_poem_date_heading=last_poem['date'].strftime("%Y-%m-%dT%H:%M:%S"),
                           last_poem=make_poem_html(last_poem['poem'], 'poemarchiveline'),
                           last_keywords=make_keyword_html(last_poem['keywords']),
                           contact_form=contact_form,
                           contact_form_success=contact_form_success,
                           jump_to_contact=jump_to_contact)
예제 #31
0
파일: app.py 프로젝트: enginhu/mekanikproje
def index():
    form = ContactForm()
    if form.validate_on_submit():
        send_email(subject="Webmail",
                   sender=form.email.data,
                   reply_to=form.email.data,
                   recipients=["*****@*****.**"],
                   mesaj=form.message.data,
                   email=form.email.data,
                   phone=form.phone.data)
        flash(_('Your message has been sent.'), 'success')
    home_projects = Project.query.filter_by(show_in_home=True)
    return render_template('index.html',
                           home_projects=home_projects,
                           form=form)
예제 #32
0
def contact():
    form = ContactForm()

    if form.validate() == False:
        return 'Error. All fields not filled in'
    else:
        msg = Message("Message from your visitor" + form.name.data,
                      sender='*****@*****.**',
                      recipients=['*****@*****.**'])
        msg.body = """
            From: %s <%s>,
            %s
            """ % (form.name.data, form.email.data, form.message.data)
        mail.send(msg)
        return redirect(url_for('home'))
예제 #33
0
def contact():
    form = ContactForm()
    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data
        message = form.message.data
        print(name)
        print(email)
        print(message)
        # db logic goes here
        print("\nData received. Now redirecting ...")
        flash("Message Received", "success")
        return redirect(url_for('contact'))

    return render_template('contact.html', form=form)
예제 #34
0
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', '*****@*****.**'),
                ['*****@*****.**'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm(initial={'subject': 'I love your site!'})
    return render_to_response('contact_form.html', {'form': form})
예제 #35
0
def contact(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', '*****@*****.**'),
                ['*****@*****.**'],
            )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm()
    return render(request, 'contact_form.html', {'form': form})
예제 #36
0
def get_contact(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['from_email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email, ['*****@*****.**'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('thanks')
    return render(request, "contacts.html", {'form': form})
예제 #37
0
파일: runner.py 프로젝트: PAY2109/ToDoList
def leave_feedback():
    form = ContactForm()
    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data
        message = form.message.data

        feedback = Feedback(name=name, email=email, message=message)
        db.session.add(feedback)
        db.session.commit()

        flash("Message Received", "success")
        return redirect(url_for('leave_feedback'))

    return render_template('feedback.html', form=form)
예제 #38
0
def loadMore(number):
    form = ContactForm()
    loadMore = False

    brandShowList = session.query(
        Brands).all()  #brandShow()#ast.literal_eval(json.dumps(brandShow()))
    varBrandShow = []

    products = []
    if len(brandShowList) >= (8 * int(number)):
        for i in range(8 * int(number)):
            varBrandShow.append(brandShowList[i])
    else:
        varBrandShow = brandShowList

    if len(varBrandShow) < len(brandShowList):
        loadMore = True

    if request.method == 'POST':
        if form.validate() == False:
            flash('All fields are required.')
            return render_template('index.html',
                                   form=form,
                                   number=int(number),
                                   brands=varBrandShow,
                                   loadMore=loadMore)
        else:
            msg = Message("Top Perfum Message",
                          sender='*****@*****.**',
                          recipients=['*****@*****.**'])
            msg.body = """
			From: %s <%s>
			Message: %s
			""" % (form.name.data, form.email.data, form.message.data)
            mail.send(msg)

            return render_template('index.html',
                                   success=True,
                                   form=form,
                                   number=int(number),
                                   brands=varBrandShow,
                                   loadMore=loadMore)

    return render_template('index.html',
                           form=form,
                           number=int(number),
                           brands=varBrandShow,
                           loadMore=loadMore)
예제 #39
0
def index():
    """
	This is the home page of the website
	:return:
	"""
    form = ContactForm()
    return render_template("index.html", form=form)
예제 #40
0
def contact():
    form = ContactForm()
    if request.method == 'POST':
        return 'Form posted.'
    elif request.method == 'GET':
        return render_template('contact.html', form=form)
    return render_template('contact.html', form=form)
예제 #41
0
def edit_contact(contact):
    if 'email' not in session:
        return redirect(url_for('login'))
    form = ContactForm()
    contactDetail = db_session.query(Contact).filter_by(
        contactId=contact).first()
    if request.method == 'POST':
        useremail = db_session.query(User).filter_by(
            id=contactDetail.UserId).first()
        if useremail.email == session['email']:
            if form.email.data != contactDetail.email:
                contactDetail.email = form.email.data
            if form.address.data != contactDetail.address:
                contactDetail.address = form.email.data
            if form.phone_number.data != contactDetail.phoneNumber:
                contactDetail.phoneNumber = form.phone_number.data
            db_session.commit()
            flash('Contact has been updated.')
            return redirect(url_for('contacts'))
        else:
            flash('This is not your account')
            return redirect(url_for('contacts'))

    elif request.method == 'GET':
        form.first_name.content = contactDetail.name
        form.last_name.content = contactDetail.name
        form.phone_number.content = contactDetail.phoneNumber
        form.email.content = contactDetail.email
        form.address.content = contactDetail.address
        return render_template('editcontact.html',
                               contact=contactDetail,
                               form=form)
예제 #42
0
def contact():
    form = ContactForm(request.form)
    if request.method == 'POST' and form.validate():
        message = form.message.data.replace('\n', '<br>')
        msg = Message(subject='Web contact form from ' + form.name.data,
                      recipients=['*****@*****.**'])
        msg.html = '''
            <b>Name:</b> %s <br>
            <b>Email:</b> %s <br>
            <b>Phone:</b> %s <br><br>
            <b>Message</b><br><br> %s
            ''' % (form.name.data, form.email.data, form.phone.data, message)
        mail.send(msg)
        return render_template('message_sent.html')
    else:
        return render_template('contact.html', form=form)
예제 #43
0
파일: views.py 프로젝트: j-planet/mysite
def contact_post(request):
    form = ContactForm(request.POST)

    if form.is_valid():
        cd = form.cleaned_data

        # send_mail(
        #     cd['subject'],
        #     cd['message'],
        #     cd.get('email', '*****@*****.**'),
        #     ['*****@*****.**'],
        # )

        return HttpResponseRedirect('thanks')
    else:
        return render(request, 'contact_form.html', {'form': form})
예제 #44
0
파일: views.py 프로젝트: hamioo66/mysite
def contact(request):
    if request.method =='post':
        form = ContactForm(request.POST)
        if form.is_valid():
            topic =form.cleaned_data['topic']
            message = form.cleaned_data['message']
            sender = form.cleaned_data.get('sender', '*****@*****.**')
            send_mail(
                'Feedback from your site,topic' % topic,
                message,sender,
                ['*****@*****.**']
            )
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm()
    return render_to_response('../templates/contact.html',{'form':form})
예제 #45
0
def contact():
    form = ContactForm()
    if (request.method == 'POST') and form.validate_on_submit():
        name = form.name.data
        email = form.email.data
        subject = request.form['subject']
        message = request.form['message']
        msg = Message(subject,
                      sender=(name, email),
                      recipients=["*****@*****.**"])
        msg.body = message
        mail.send(msg)
        flash('Message Sent')
        return redirect(url_for('home'))

    return render_template('contact.html', form=form)
예제 #46
0
def contact():
  form = ContactForm()
  if request.method == 'POST':
    if form.validate() == False:
      return render_template('contact.html', form=form)
    else:
      msg = Message("Crackfic: " + form.subject.data, sender='*****@*****.**', recipients=['*****@*****.**'])
      msg.body = """
      From: %s <%s>
      %s
      """ % (form.name.data, form.email.data, form.message.data)
      mail.send(msg)
      return redirect(url_for("sent"))
 
  elif request.method == 'GET':
    return render_template('contact.html', form=form)
예제 #47
0
def contact():
    form = ContactForm(request.form)
    if request.method == "POST" and form.validate():
        send_email(
            to=DEFAULT_EMAIL,
            subject="You got a message",
            template="contact.html",
            email=form.email.data,
            message=form.message.data,
            phone=form.phone.data,
            name=form.name.data,
            sender_subject=form.subject.data,
        )
        flash("Your message was sent successfully!")
        return redirect(url_for("contact"))
    return render_template("pages/contact-us.html", form=form)
예제 #48
0
 def post(self, request):
     form = ContactForm(request.POST)
     if not form.is_valid():
         messages.error(request, "Looks like your captcha was wrong!")
         return render(request, 'accounts/contact.html', {'form': form})
     else:
         mail_admins(
             "New contact form submission from {0}".format(
                 form.cleaned_data['email']),
             form.cleaned_data["feedback"],
         )
         messages.success(
             request,
             "Thank you! We'll get back to you as soon as possible.")
         return render(request, 'accounts/contact.html',
                       {'form': ContactForm()})
예제 #49
0
def contact():
    form = ContactForm()
    if request.method == 'POST':
        if form.validate() == False:
            flash("All field are required")
            return render_template('contact.html', form=form)
        else:
            msg = Message(request.form['subject'],
                          sender=(request.form['name'], request.form['email']),
                          recipients=['*****@*****.**'])
            msg.body = form.message.data
            mail.send(msg)
            flash("Message was successfully sent")
            return redirect(url_for('home'))
    else:
        return render_template('contact.html', form=form)
예제 #50
0
파일: routes.py 프로젝트: jakebas/homepage
def contact():
  form = ContactForm()

  if request.method == 'POST':
    if not form.validate():
      return render_template('contact.html', form=form)
    else:
      msg = Message(form.subject.data, sender="*****@*****.**", recipients=['*****@*****.**'])
      msg.body = """
      From: %s <%s>
      %s
      """ % (form.name.data, form.email.data, form.message.data)
      mail.send(msg)
      return render_template('contact.html', success=True)
  elif request.method == 'GET':
    return render_template('contact.html', form=form)
예제 #51
0
def login():
    form = ContactForm()

    if request.method == 'POST':
        username = form.name.data
        password = form.password.data
        cursor = mysql.connect().cursor()
        cursor.execute("SELECT * from User where Username='******' and Password='******'")
        data = cursor.fetchone()  # define after this ?
        if data is None:
            flash("Username or Password is wrong")
            return redirect(url_for('login'))
        else:
            session['logged_in'] = True
            #what does this do? After i comment it, it still works anyway, yet all the tutorials are saying it.
            session[
                'username'] = username  # Is it the right way to give the session a temporary id?
            print(
                session
            )  #seems doesn't work, how can i know whether i'm in the session?
            # flash('Logged in successfully')
            # return render_template('login.html', form=form)
            return redirect(url_for('mypage'))

    elif request.method == 'GET':
        return render_template('login.html', form=form)
예제 #52
0
def contact():
    results = {}  # data struct to hold vars
    form = ContactForm()
    results["status"] = None

    # get all the data from what the user entered
    # onto the form and validate the spam checker
    if request.method == 'POST':
        print form.spam.data

        # validate the spam checker
        # return error if it is not correct
        if form.spam.data != "1":
            results["status"] = "error"
            form.name.data = form.name.data
            return render_template('contact.html', results=results, form=form)

        # if pass the spam checker, generate a message and send it
        msg = Message("[whatcanifarm] email has arrived!",
                      sender=app_email,
                      recipients=[app_email])
        msg.body = """ 
        From: %s <%s> 
        %s
        """ % (form.name.data, form.email.data, form.message.data)
        mail.send(msg)

        # set success status and render the same page with the success alert
        results["status"] = "success"
        return render_template('contact.html', results=results, form=form)

    elif request.method == 'GET':
        return render_template('contact.html', results=results, form=form)
예제 #53
0
def register():
    form = ContactForm()

    if request.method == 'POST':
        newusername = form.name.data
        newpassword = form.password.data
        print form.name.data
        print form.password.data
        # cursor = mysql.connect().cursor()
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute("SELECT * from User where Username='******'")
        conn.commit()
        data = cursor.fetchone()
        if data is None:
            cursor.execute(
                "INSERT INTO user (userName,password) VALUES ('{0}', '{1}')".
                format(newusername, newpassword))
            conn.commit()
            flash('Congratulations, you have successfully registered!')
            return redirect(url_for('login'))
        else:
            flash(
                'The username is currently been used, smart as you must can come up with another one'
            )
            return redirect(url_for('login'))
    elif request.method == 'GET':
        return render_template('register.html', form=form)
예제 #54
0
 def GET(self):
     if self.request.user.is_authenticated():
         form = ContactForm()
     else:
         form = AnonymousContactForm()
     return self.context_response('main/contact.html', {'form': form,
         'current_tab': 'contact'})
예제 #55
0
def reach_out():
    form = ContactForm()
    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data
        message = form.message.data

        msg = Message(f"Message from {name}",
                      sender=f"{email}",
                      recipients=['*****@*****.**'])
        msg.body = f"{message} from {email}"

        mail.send(msg)
        flash("Email sent", "success")
        return redirect('/')
    return render_template("contact.html", form=form)
예제 #56
0
파일: views.py 프로젝트: wangkaigithub/lang
def contact(request):
    if request.method == 'POST':  # 处理用户提交动作
        # ContactForm会自动校验用户输入.
        form = ContactForm(request.POST)
        if form.is_valid():
            topic = form.data['topic']
            message = form.data['message']
            sender = form.data.get('sender', '*****@*****.**')
            send_mail('Feedback from your site, topic: %s' % topic, message,
                      sender, ['*****@*****.**'])
            # 在一个POST请求过后, 如果用户选择刷新页面, 这个请求就重复提交了.
            # 在POST之后重定向页面是一个有用的模式, 可以避免这样的情况出现.
            return HttpResponseRedirect('/contact/thanks/')
    else:
        form = ContactForm(initial={'sender': '*****@*****.**'})
    return render_to_response('books/contact.html', {'form': form})
예제 #57
0
def forgotPassword(request, forgotID=False):
    if forgotID:
        #check that it has been less than 5 minutes since forgotID was created.
        if ForgottenPassword.objects.filter(id=forgotID):
            forgot = ForgottenPassword.objects.get(id=forgotID)

            now = timezone.now()
            tdelta = now - forgot.dateTime
            seconds = tdelta.total_seconds()

            if not seconds:# > 300 or forgot.used:
                return HttpResponse('You reached this link in error.'+str(seconds))
            else:
                forgot.used = True
                forgot.save()

                args = {}
                args.update(csrf(request))
                args['passwordForm'] = ContactForm()
                return render_to_response('google_login/change_password.html', args)
        else:
            return HttpResponse('You reached this link in error.')

        #Set the dateTime to 0 so that this link will only work once.
    else:
        return HttpResponse('You reached this link in error.')
예제 #58
0
파일: views.py 프로젝트: tonlog/tonlog
def contactUs(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            topic = form.cleaned_data['topic']
            message = form.cleaned_data['message']
            sender = form.cleaned_data['sender']
            send_mail('feedback for you: %s' % (topic,),
                message,
                sender,
                [DEFAULT_MAIL_RECEIVER],
            )
            return HttpResponseRedirect("/contactUs/thx")
    else:
        form = ContactForm()
    return render_to_response("contactUs.html",{'form':form},context_instance=RequestContext(request))
예제 #59
0
def contact():
    form = ContactForm()

    if request.method == 'POST':
        if form.validate() == False:
            print "!! All fields are required!!"
            flash('All fields are required.')

            return render_template('contact.html', form=form)
        else:
            print form.name.data
            print form.language.data
            return render_template('success1.html', form=form)

    elif request.method == 'GET':
        return render_template('contact.html', form=form)
예제 #60
0
def contact():
    form = ContactForm(request.form)

    if request.method == 'POST' and form.validate():
        msg = Message(form.subject.data,
                      sender='*****@*****.**',
                      recipients=['*****@*****.**'])
        msg.body = """
    From: %s <%s>
    %s
    """ % (form.name.data, form.email.data, form.message.data)
        mail.send(msg)

        return render_template('contact.html', success=True)
    else:
        print form.data
        return render_template('contact.html', form=form)