def make_valid(self, **kwargs): valid = dict(nome='thiago', sobre_nome='oliveira', obeservacao='teste formulario') data = dict(valid, **kwargs) form = ContactForm(data) form.is_valid() return form
def test_send_mail(self): form1 = ContactForm(data=self.data) form1.is_valid() res1 = form1.send_mail() form2 = self.form form2.is_valid() res2 = form2.send_mail() self.assertEquals(res1, res2)
def contact(request): sent = request.GET.get("sent", "").lower() == "true" if request.method == "GET": data = {} if request.user and not request.user.is_anonymous: data["name"] = request.user.first_name or request.user.username data["email"] = request.user.email form = ContactForm(data=data) elif request.method == "POST": form = ContactForm(data=request.POST) if form.is_valid(): data = form.cleaned_data email = EmailMessage( subject=f"Contato no Brasil.IO: {data['name']}", body=data["message"], from_email=f'{data["name"]} (via Brasil.IO) <{settings.DEFAULT_FROM_EMAIL}>', to=[settings.DEFAULT_FROM_EMAIL], reply_to=[f'{data["name"]} <{data["email"]}>'], ) email.send() return redirect(reverse("core:contact") + "?sent=true") else: context = {"message": "Invalid HTTP method."} return render(request, "404.html", context, status=400) return render(request, "contact.html", {"form": form, "sent": sent})
def contact_user(request): user_id = None user = None contact_form = None if request.method == "POST": contact_form = ContactForm(data = request.POST) if contact_form.is_valid(): to_user = get_object_or_404(get_user_model(), id = contact_form.cleaned_data['user_id'] ) message = contact_form.cleaned_data['message'] context = Context({'to_user': to_user.get_profile().get_display_name(), 'from_user': request.user.get_profile().get_display_name(), 'from_user_id': request.user.pk, 'message': message }) title = "User %s has sent you a message via BuddhistExchange. " % request.user.get_profile().get_display_name() send_email('contact-user.txt', context, title, to_user.email) return HttpResponse('<script type="text/javascript">document.write("Your message has been sent.");window.close();opener.alert("You email message has been sent.");</script>') else: user_id = int(request.GET.get('user_id')) user = get_object_or_404(get_user_model(), id = user_id ) contact_form = ContactForm(initial = request.GET) context = {"form": contact_form, "user": user} if not request.user.is_authenticated(): return HttpResponse('<script type="text/javascript">alert("Please login to your account before you access the contact link.");document.location="/";</script>') return render(request, 'contact.html', context)
def 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'] from_email = settings.DEFAULT_FROM_EMAIL body = form.cleaned_data['body'] name = form.cleaned_data['name'] try: logging.info( 'subject:{} body:{} from_email:{} DEFAULT_TO_EMAIL:{}', subject, body, from_email, settings.DEFAULT_TO_EMAIL) send_mail(subject, body, from_email, [settings.DEFAULT_TO_EMAIL], fail_silently=False) except BadHeaderError as bhe: messages.error(request, "Houston there was a problem") logging.exception('Exception occurred: BadHeaderError') return HttpResponse('Invalid header found.') except gaierror: messages.error(request, "Email server unavailable") logging.exception('Exception occurred: gaierror') # return HttpResponse('Email server is down.') return render(request, "core/contact.html", {'form': form}) return redirect('success') return render(request, "core/contact.html", {'form': form})
def contact(request, title='Contact Us', success_url='/contact/thanks/'): 'Contact Us form' form = ContactForm(request.POST or None) if request.method == 'POST': if form.is_valid(): msg = u'Contact message from {name} ({email}): {message}'.format( name = form.cleaned_data['name'], email = form.cleaned_data['email'], message = form.cleaned_data['message'] ) logging.info(msg) # Save it in case email is lost email_msg = (u'Contact message from {name} ({email}):\n'+ u'IP Address: {ip}\n'+ u'Browser: {browser}\n'+ u'\n'+ u'{message}\n') mail_admins('Message via Contact Form', email_msg.format( name = form.cleaned_data['name'], email = form.cleaned_data['email'], ip = request.META['REMOTE_ADDR'], browser = request.META['HTTP_USER_AGENT'], message = form.cleaned_data['message'] ) ) return HttpResponseRedirect(success_url) return render_to_response('contact.html', {'form': form, 'title': title}, context_instance=RequestContext(request))
def post(self, request): page = Page.objects.get(url='contact') form = ContactForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/core/pages/thanks') else: return self.do_render(request, form)
def contacts(request): if request.method == "POST": if request.POST.get("im_bot") == "on": return HttpResponseForbidden("Seems that you are a bot.") data = (request.POST).copy() if settings.RECAPTCHA_TESTING: data["recaptcha_response_field"] = "PASSED" contact_form = ContactForm(data) if contact_form.is_valid(): send_mail(ugettext("Email via {}").format(settings.SITE_TITLE), data["message"], data["email"], [settings.AUTHOR_EMAIL]) return redirect("blog_articles") else: data = { "email": "", "message": "", } contact_form = ContactForm() captcha = ReCaptcha(attrs={"theme": "clean"}).render(None, None) return render_to_response("contacts.html", { "page_title": ugettext("Contacts"), "contact_form": contact_form, "data": data, "captcha": captcha, }, context_instance=RequestContext(request))
def contact(request): context = {} context["new_job_form"] = JobForm if request.method == "POST": form = ContactForm(request.POST or None) recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': config('RECAPTCHA_SECRET_KEY'), 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if form.is_valid() and result['success']: form.save() context["message_first"] = "Mensagem enviada com sucesso", context["message_second"] = "Vá para a home do site!" return render(request, template_name="generic.html", context=context) else: context["message_first"] = "Falha na hora de mandar a mensagem", context[ "message_second"] = "Você preencheu algum campo da maneira errada, tente novamente!" return render(request, template_name="generic.html", context=context) context["form"] = ContactForm return render(request, "contact-us.html", context)
def contact(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] company = form.cleaned_data['company'] message = form.cleaned_data['message'] template = get_template('core/contact_template.txt') context = { 'name': name, 'email': email, 'phone': phone, 'company': company, 'message': message, } content = template.render(context) email = EmailMessage("new contact form submission", content, "Your website" + '', ['*****@*****.**'], headers={'Reply-To': email}) email.send() messages.success(request, 'Thank you! We will be in touch.') return redirect('contact') else: form = ContactForm() return render(request, 'core/contact.html', {'form': form})
def contact(request): success = False form = ContactForm(request.POST or None) if form.is_valid(): form.send_mail() success = True context = {'form': form, 'success': success} return render(request, 'contact/contact.html', context)
def test_contact_valid(self): """test_contact_form_validation() checks form with is_valid() method.""" form = ContactForm( data={ 'name': 'Tester', 'email': '*****@*****.**', 'subject': 'testoo', 'message': 'Test test test.' }) self.assertTrue(form.is_valid())
def aboutview(request): cats = Category.objects.all() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() # does nothing, just trigger the validation else: form = ContactForm() return render(request, 'core/about.html', {'cats': cats, 'form': form})
def contact_us(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() message = "Your query is submitted and will be reviewed by administrator soon ." else: message = "Kindly check submitted data or there may be maintenance activity going on." else: form=ContactForm() current='contact' return render_to_response('contact_us.html', locals(), context_instance = RequestContext(request))
def add_contact(request): context = RequestContext(request) if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print form.errors else: form = ContactForm() return render_to_response('add_contact.html', {'form':form}, context)
def post(self, request, format=None): form = ContactForm(request.data) if form.is_valid(): form.send_email() return Response({'success': 'Email enviado'}, status=status.HTTP_200_OK) else: errors = { field: errors[0] for field, errors in form.errors.items() } return Response(errors, status=status.HTTP_400_BAD_REQUEST)
def index(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save(commit=True) # return index(request) else: print(form.errors) return render(request, 'careerhelp/index.html', {'form': form})
def contact(request): if request.method != 'POST': title = "contact page" form = ContactForm() context = {'title': title, 'form': form} return render(request, 'core/contact.html', context) else: form = ContactForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Message Sent successfully") return render(request, 'core/contact.html')
def contact_form(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data superusers_emails = CustomUser.objects.filter(is_superuser=True).values_list('email', flat=True) subject = f"Contact form from: {cd['name']} {cd['surname']}" send_mail(subject, cd['message'], settings.EMAIL_HOST_USER, superusers_emails) return render(request, 'core/form-confirmation.html') else: messages.warning(request, 'Got error while sending a contact form. All fields required.') return render(request, 'core/base.html', {'form': form})
def detail(request, id): contato = get_object_or_404(Contact, id=id) if request.method == 'POST': form = ContactForm(request.POST, instance=contato) if form.is_valid(): novo_contato = form.save() return HttpResponseRedirect(reverse('url:core_forms')) else: form = ContactForm(instance=contato) return render(request, 'core/detail.html', { 'contato': contato, 'form': form, })
def contact(request): if request.method == "POST": contact_form = ContactForm(request.POST) if contact_form.is_valid(): send_mail( "Knight Book Market Support", "From: %s\nReason: %s\n\n%s" % (request.POST["email"], request.POST["reason"], request.POST["message"]), "settings.EMAIL_HOST_USER", ["*****@*****.**"], ) return message_page(request, u"Thanks for contacting us!") else: contact_form = ContactForm() return load_page(request, "contact-report.html", {"form": contact_form})
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sujet = form.cleaned_data['sujet'] message = form.cleaned_data['message'] envoyeur = form.cleaned_data['envoyeur'] renvoi = form.cleaned_data['renvoi'] envoi = True else: form = ContactForm() return render(request, 'core/contact.html', locals())
def contactView(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('success') return render(request, "email.html", {'form': form})
def formulario(request): contatos = Contact.objects.all() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): novo_contato = form.save() return HttpResponseRedirect(reverse('url:core_forms')) else: form = ContactForm() return render(request, 'core/index.html', { 'contatos': contatos, 'form': form })
def contact(request): success = False name, email, message = None, None, None contact_sent = request.session.get('contact_sent', False) if request.method == 'POST': contact_form = ContactForm(request.POST) if request.session.test_cookie_worked(): print 'WORKED' else: print 'DOES NOT WORK' if contact_form.is_valid(): success = True data_contact = DataContact() data_contact.name = contact_form.cleaned_data['name'] data_contact.email = contact_form.cleaned_data['email'] data_contact.message = contact_form.cleaned_data['message'] request.session['data_contact'] = data_contact name = request.session['data_contact'].name email = request.session['data_contact'].email message = request.session['data_contact'].message print data_contact.name print data_contact.email print data_contact.message request.session['contact_sent'] = True else: contact_form = ContactForm() context = { 'success': success, 'contact_sent': contact_sent, 'contact_form': contact_form, 'name': name, 'email': email, 'message': message, } request.session.set_test_cookie() return render(request, 'core/contact.html', context)
def contact(request): success = False form = ContactForm(request.POST or None) if form.is_valid(): form.send_email() success = True elif request.method == 'POST': messages.error( request, 'Formulário inválido. Preencha todos os campos corretamente.') context = { 'form': form, 'success': success, } return render(request, 'contact.html', context)
def contact(request): form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject=subject, message=message, from_email=email, recipient_list=['*****@*****.**'], fail_silently=False) return HttpResponse('OK', status=200) except BadHeaderError: return HttpResponse(status=400) else: return HttpResponse(status=400)
def emailView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['Assunto'] from_email = form.cleaned_data['Email'] message = form.cleaned_data['Messagem'] fullMessage = "Email do cliente: " + from_email + '\n' '\n' + message try: send_mail(subject, fullMessage, from_email, ['*****@*****.**']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('index') return render(request, "core/contact.html", {'form': form})
def contact(request): success = False # Entede-se aqui como sendo uma operação ternária em Python. Caso a avaliação # boolena do primeira termo serja False, não existente, ele envia um None. # Se estamo passando um None, o DJango entende que nosso formulario nao está # preenchido e sem validar, o que não mostra mensagem de erro. Seria como uma # nova instanciação do mesmo: form = ContactForm() form = ContactForm(request.POST or None) if form.is_valid(): form.send_mail() success = True context = { 'title': 'Fale Conosco', 'form': form, 'success': success, } return render(request, 'contact.html', context)
def send_contactmail(request): ''' Called via ajax. ''' context = RequestContext(request) status = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() status = True else: form = ContactForm() return render_to_response('core/contact_form.html', { 'form': form, 'success': status }, context)
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Website Inquiry" body = { 'name': form.cleaned_data['name'], 'email': form.cleaned_data['email'], 'message': form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message, 'email', ['*****@*****.**']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect("home") form = ContactForm() return render(request, "core/contact.html", {'form': form})
def add_contact_to_project(request, pk): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): project = get_object_or_404(Project, pk=pk) contact = form.save() project.contacts.add(contact) project.save() add_message(request, messages.SUCCESS, "Contact added") else: error_messages = [] for field, error in form.errors.items(): error_message = f"{field}: {error[0]}" error_messages.append(error_message) add_message(request, messages.ERROR, "\n".join(error_messages)) return redirect(to='project', pk=pk) else: form = ContactForm() return render(request, 'modal_form.html', {'form': form, 'submit_url': request.get_full_path()})
def contact(request): if request.method == "POST": form = ContactForm(request.POST or None) if form.is_valid(): form.save() return render(request, template_name="generic.html", context={ "message_first": "Mensagem enviada com sucesso", "message_second": "Vá para a home do site!" }) else: return render( request, template_name="generic.html", context={ "message_first": "Falha na hora de mandar a mensagem", "message_second": "Você preencheu algum campo da maneira errada, tente novamente!" }) return render(request, "contact-us.html", {"form": ContactForm})
def contato(request): from core.forms import ContactForm form = ContactForm(request.POST or None) if request.method == 'POST': if form.is_valid(): sender = form.cleaned_data.get("sender") subject = form.cleaned_data.get("subject") message = form.cleaned_data.get("message") if subject and message and sender: # from django.core.mail import send_mail, BadHeaderError # try: # send_mail(subject, message, sender, ['*****@*****.**'], fail_silently=False) # except BadHeaderError: # return HttpResponse('Invalid header found.') # return HttpResponseRedirect('/') from django.core import mail connection = mail.get_connection() # Manually open the connection connection.open() # Construct an email message that uses the connection email1 = mail.EmailMessage( subject, message, sender, ['*****@*****.**'], connection=connection, ) email1.send() connection.close() else: return HttpResponse('Make sure all fields are entered and valid.') return render(request, 'contato.html', {'form': form})
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['*****@*****.**']) except BadHeaderError: return HttpResponse('invalid header') return redirect('core:send_success') else: form = ContactForm() context = { 'form': form } return render(request, 'contact.html', context)