def test_form_valid(self): """Todos los campos son requeridos.""" self.assertTrue(self.form.is_valid()) # Sin campo subject. form_data = self.form_data form_data['subject'] = '' form = ContactForm(data=form_data) self.assertFalse(form.is_valid()) # Sin campo message. form_data = self.form_data form_data['message'] = '' form = ContactForm(data=form_data) self.assertFalse(form.is_valid()) # Sin campo username. form_data = self.form_data form_data['username'] = '' form = ContactForm(data=form_data) self.assertFalse(form.is_valid()) # Sin campo username. form_data = self.form_data form_data['email'] = '' form = ContactForm(data=form_data) self.assertFalse(form.is_valid())
def test_contact_form(self): """ Check if contact form validation is working properly. """ invalid_data_dicts = [ # Empty subject {'data': {'subject': '', 'sender_name': 'Steve Tester', 'sender_email': '*****@*****.**', 'message': 'This is my test message', 'cc_myself': 'False'}, 'error': ('subject', ['This field is required.'])}, # Empty message {'data': {'subject': 'Test subject', 'sender_name': 'Steve Tester', 'sender_email': '*****@*****.**', 'message': '', 'cc_myself': 'False'}, 'error': ('message', ['This field is required.'])}, ] for invalid_dict in invalid_data_dicts: form = ContactForm(data=invalid_dict['data']) self.failIf(form.is_valid()) self.assertEqual(form.errors[invalid_dict['error'][0]], invalid_dict['error'][1]) form = ContactForm(self.valid_data) self.failUnless(form.is_valid())
def contact(request): template = "contact_us.html" form = ContactForm() if request.method == "POST": form = ContactForm(request.POST) print form.is_valid() if form.is_valid(): send_mail("Test mail", "Hi {}, This is the test mail".format( form.cleaned_data['name']), settings.DEFAULT_FROM_EMAIL, [form.cleaned_data['email']], fail_silently=True) messages.success(request, "Mail sent successfully !") return render(request, template, {'form': form})
def test_contact_form_subject(admin, rf, mailoutbox): request = rf.request() request.user = admin data = { 'name': admin.full_name, 'email': admin.email, 'email_subject': "a" * 101, 'body': "Whatever", } form = ContactForm(request=request, data=data) assert not form.is_valid() data['email_subject'] = "a" * 100 form = ContactForm(request=request, data=data) assert form.is_valid()
def index(request): form = ContactForm() if request.method == 'POST': form = ContactForm(data=request.POST) if form.is_valid(): setting = Setting.objects.get(pk=1) email = EmailMessage(subject=form.data['subject'], body=form.data['message'], from_email=setting.email, to=[setting.email], reply_to=[form.data['email']]) try: email.send() message_response = 'Mensaje enviado! Te contactaremos lo más pronto posible ;)' type_respose = 'success' except ValueError: message_response = 'Oops! Algo salio mal, intentalo más tarde :P' type_respose = 'danger' return JsonResponse({ 'message': message_response, 'type': type_respose }) context = {"form": form} return render(request, "contact/index.html", context)
def serve(self, request): from contact.forms import ContactForm, ContactMatterForm if request.method == 'POST': contact_form = ContactForm(request.POST) contact_matter_form = ContactMatterForm(request.POST) if contact_form.is_valid() and contact_matter_form.is_valid(): contact = contact_form.save() matter = contact_matter_form.save(commit=False) matter.contact = contact matter.save() messages.success( request, self.success_messages['successful_submission']) return redirect(self.url) else: contact_form = ContactForm() contact_matter_form = ContactMatterForm() return render( request, 'contact/contact_page.html', { 'page': self, 'contact_form': contact_form, 'contact_matter_form': contact_matter_form })
def contact_create_or_edit(request, id=None): if id: title = _('Edit a contact') contact = get_object_or_404(Contact, pk=id, owner=request.user) address = contact.address else: title = _('Add a contact') contact = None address = None PhoneNumberFormSet = inlineformset_factory(Contact, PhoneNumber, form=PhoneNumberForm, fk_name="contact", extra=1) contacts = Contact.objects.filter(owner=request.user) if contact: contacts = contacts.exclude(pk=contact.id) if request.method == 'POST': contactForm = ContactForm(request.POST, instance=contact, prefix="contact") contactForm.fields['contacts'].queryset = contacts addressForm = AddressForm(request.POST, instance=address, prefix="address") phonenumberformset = PhoneNumberFormSet(request.POST, instance=contact) if contactForm.is_valid() and addressForm.is_valid() and phonenumberformset.is_valid(): user = request.user address = addressForm.save(commit=False) address.save(user=user) contact = contactForm.save(commit=False) contact.address = address contact.save(user=user) contactForm.save_m2m() for phonenumberform in phonenumberformset.forms: phonenumber = phonenumberform.save(commit=False) if phonenumber.type: phonenumber.contact = contact phonenumber.save(user=user) for deleted_phonenumberrowform in phonenumberformset.deleted_forms: deleted_phonenumberrowform.cleaned_data['ownedobject_ptr'].delete() messages.success(request, _('The contact has been saved successfully')) return redirect(reverse('contact_detail', kwargs={'id': contact.id})) else: messages.error(request, _('Data provided are invalid')) else: contactForm = ContactForm(instance=contact, prefix="contact") contactForm.fields['contacts'].queryset = contacts addressForm = AddressForm(instance=address, prefix="address") phonenumberformset = PhoneNumberFormSet(instance=contact) return render_to_response('contact/edit.html', {'active': 'contact', 'title': title, 'contactForm': contactForm, 'addressForm': addressForm, 'phonenumberformset': phonenumberformset}, context_instance=RequestContext(request))
def contact_page(request): if request.method == 'POST': contact_form = ContactForm(request.POST or None) if contact_form.is_valid(): print(contact_form.cleaned_data) sender_name = contact_form.cleaned_data['name'] sender_email = contact_form.cleaned_data['email'] content = "{0} has sent you a new message:\n\n{1}".format( sender_name, contact_form.cleaned_data['content']) send_mail('New Enquiry', content, sender_email, ['*****@*****.**']) return HttpResponseRedirect('success') else: contact_form = ContactForm() # if request.method == "POST": # #print(request.POST) # print(request.POST.get('fullname')) # print(request.POST.get('email')) # print(request.POST.get('content')) context = { "title": "Contact", "content": " Welcome to the contact page.", "form": contact_form, } return render(request, "contact/view.html", context)
def post(self, request, id): cek_session(request) if request.session.get('active_elder') is not None and request.session[ 'active_elder'] != 0: elder = Elder.objects.get(pk=request.session.get('active_elder')) elders = Elder.get_cared_elder(user=CareGiver.objects.get( user=request.user)) contact = Contact.objects.filter( elder=elder, id=id, added_by=CareGiver.objects.get(user=request.user)) if contact: form = ContactForm(request.POST, instance=contact[0]) if form.is_valid(): contact = form.save() return render( request, 'contact_edit.html', { 'elders': elders, 'success': "Data berhasil dirubah", 'active_elder': elder, 'contact': contact }) return render( request, 'contact_edit.html', { 'elders': elders, 'active_elder': elder, 'error': form.errors, 'contact': contact[0] }) return HttpResponseRedirect(reverse('contact')) return HttpResponseRedirect(reverse('index'))
def general(request): template_name = "contact/general.html" if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): if request.POST.get("complete") == "1": _notify_sender(form.cleaned_data, request) messages.add_message(request, messages.SUCCESS, "お問い合わせを承りました。確認のメールを送信しました。") return redirect("home") elif not request.POST.get("complete"): template_name = "contact/general_confirm.html" else: # ログインしてたら登録情報をセット if request.user.is_authenticated(): u = request.user p = u.myuserprofile form = ContactForm( initial={ "email": u.email, "first_name": p.first_name, "last_name": p.last_name, "department": p.department, "company_name": p.company_name, "tel": p.tel, "fax": p.fax, "site_url": p.site_url, } ) else: form = ContactForm() return render_to_response(template_name, {"form": form}, context_instance=RequestContext(request))
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): name = request.POST.get('name', '') email = request.POST.get('email', '') topic = request.POST.get('subject', '') content = request.POST.get('content', '') from_email = Email(email) subject = topic content = Content("text/plain", content + "\n\n\n" + name) mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) print(response.status_code) print(response.body) print(response.headers) return redirect('success') else: return render(request, 'contact/home.html', {'form': form}) else: form = ContactForm() return render(request, 'contact/home.html', {'form': form})
def contact(request): print('Tipo de peticion {}'.format(request.method)) contactForm = ContactForm() if request.method == 'POST': contactForm = ContactForm(request.POST) if contactForm.is_valid(): name = request.POST.get('name') email = request.POST.get('email') content = request.POST.get('content') email = EmailMessage(subject='Messaje from contact form django', body='De {} <{}>\n\nEscribio:\n\n{}'.format( name, email, content), from_email='*****@*****.**', to=[ '*****@*****.**', ], reply_to=[ email, ]) try: email.send() # if all is OK return redirect(reverse('contact') + '?ok') except: return redirect(reverse('contact') + '?fail') return render(request, 'contact/contact.html', {'form': contactForm})
def home(request): if request.method == 'POST': if request.POST['submit'] == 'Enviar mensaje': contact_form = ContactForm(request.POST) if contact_form.is_valid(): process_valid_contact_form(contact_form) return HttpResponseRedirect('/?action=gracias') else: call_me_form = CallMeForm() else: call_me_form = CallMeForm(request.POST) if call_me_form.is_valid(): process_valid_call_me_form(call_me_form) return HttpResponseRedirect('/?action=gracias') else: contact_form = ContactForm() else: contact_form = ContactForm() call_me_form = CallMeForm() carousel_list = Photo.objects.carousel() albums = Photo.objects.gallery_by_album() return render_to_response( "index.html", locals(), context_instance=RequestContext(request), )
def contact(request): """ View function for contact page of site. """ if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['sender_name'] from_email = form.cleaned_data['contact_email'] message = form.cleaned_data['content'] try: send_mail("Mangalis email: " + subject, message, from_email, ['*****@*****.**'], fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found.') ContactForm() return redirect('/contact/success') # Render the HTML template index.html with the data in the context variable return render( request, 'contact/contact.html', {'form': form}, )
def contact(request): lang = Language.objects.get(abreviation=request.LANGUAGE_CODE) if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): send_mail( 'Subject here', 'Here is the message.', '*****@*****.**', ['*****@*****.**'], fail_silently=False, ) # send email code goes here #subject_name = form.cleaned_data['subject'] #sender_name = form.cleaned_data['name'] #sender_email = form.cleaned_data['email'] #message = "{0} vous a envoyé un message - son email est {1} \n\nSon message : \n\n{2}".format(sender_name, sender_email, form.cleaned_data['message']) #send_mail(subject_name, message, sender_email, ['*****@*****.**'], fail_silently=False) return HttpResponse('Merci d' 'avoir pris contact avec nous!') else: form = ContactForm() return render(request, 'contact/contact.html', {'form': form})
def contact(request): try: username = request.user.username email = request.user.email except AttributeError: username = '' email = None form_init = { 'username': username, # 'ip_address': request.META.get('REMOTE_ADDR'), 'email': email, } if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): msg = render_to_string('contact/email.txt', form.cleaned_data) send_mail('Contact Us email form', msg, settings.EMAIL_SENDER, [settings.CONTACT_EMAIL]) messages.success(request, 'Thank you for contacting us!') return redirect(reverse('index')) else: messages.error(request, 'Boo! Hiss!') else: form = ContactForm(initial=form_init) return render(request, 'contact/contact.html', {'form': form})
def post(self, request): cek_session(request) elder = None if request.session.get('active_elder') is not None and request.session[ 'active_elder'] != 0: elder = Elder.objects.get(pk=request.session.get('active_elder')) caregiver = CareGiver.objects.get(user=request.user) elders = Elder.get_cared_elder(user=caregiver) form = ContactForm(request.POST) contact = Contact.objects.filter(elder=elder).order_by('-id') if form.is_valid(): new = form.save(commit=False) new.elder = elder new.added_by = caregiver new.save() contact = Contact.objects.filter(elder=elder).order_by('-id') return render( request, 'contact.html', { 'elders': elders, 'success': "Data berhasil ditambahkan", 'active_elder': elder, 'contact': contact }) else: return render( request, 'contact.html', { 'elders': elders, 'error': form.errors, 'active_elder': elder, 'contact': contact }) else: return HttpResponseRedirect(reverse('index'))
def home(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) # return HttpResponse(str(form)) if form.is_valid(): if form.save(): subject = form.cleaned_data['subject'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, email, ['*****@*****.**']) except BadHeaderError: return HttpResponse('Invalid header found.') messages.success(request, 'Profile details updated.') return render(request, 'contact.html') else: return HttpResponse( """your form is wrong, reload on <a href = "{{ url : 'index'}}">reload</a>""" ) else: return render(request, 'contact.html')
def contact(request): if request.method == 'POST': # S'il s'agit d'une requête POST form = ContactForm(request.POST) # Nous reprenons les données if form.is_valid( ): # Nous vérifions que les données envoyées sont valides # Ici nous pouvons traiter les données du formulaire nom = form.cleaned_data['nom'] mail = form.cleaned_data['mail'] numero = form.cleaned_data['numero'] message = form.cleaned_data['message'] try: send_mail("Message du jardin buissonnier de %s" % nom, message, mail, ['*****@*****.**']) except BadHeaderError: print("marche pas") return HttpResponse('Invalid header found.') # Nous pourrions ici envoyer l'e-mail grâce aux données que nous venons de récupérer envoi = True else: # Si ce n'est pas du POST, c'est probablement une requête GET form = ContactForm() # Nous créons un formulaire vide return render(request, 'contact/contact_accueil.html', locals())
def edit(request): try: contact = Contact.objects.all()[0] except IndexError: raise Http404 if request.method == "POST": form = ContactForm(request.POST, request.FILES, instance=contact) if form.is_valid(): form.save() if request.is_ajax(): response = {'status': 'OK'} data = {'name': 'photo', 'value': contact.photo} response['image'] = form.fields['photo'].widget.render(**data) return HttpResponse(simplejson.dumps(response)) return redirect(reverse('index')) else: if request.is_ajax(): response = {'status': 'BAD'} errors = dict() for label_id, error in form.errors.items(): errors[label_id] = error response['errors'] = errors return HttpResponse(simplejson.dumps(response)) else: form = ContactForm(instance=contact) return render_to_response('edit.html', {'form': form, 'number': FORM_SPLIT_BY}, context_instance=RequestContext(request))
def contact(request): user = request.user if request.method == 'POST': form = ContactForm(user, request.POST) if form.is_valid(): cd = form.cleaned_data subject = cd['subject'] message = cd['message'] if user.is_authenticated(): email = user.email msg = message + '\n\nFrom: ' + email mail_admins(subject, msg) messages.success(request, "Your message has been sent! Thanks.") return HttpResponseRedirect(reverse('index')) else: email = cd['email'] msg = message + '\n\nFrom: ' + email mail_admins(subject, msg) return HttpResponseRedirect(reverse('contact-success')) else: form = ContactForm(user) return render_to_response('contact/contact.html', { 'form': form, }, context_instance=RequestContext(request))
def contact(request): contact_form = ContactForm() if request.method == "POST": contact_form = ContactForm(data=request.POST) if contact_form.is_valid(): name = request.POST.get('name', '') email = request.POST.get('email', '') content = request.POST.get('content', '') # Sending email email_to_send = EmailMessage( "La Caffettiera: Nuevo mensaje de contacto", f"De {name} <{email}>\n\nEscribió:\n\n{content}", "*****@*****.**", ["*****@*****.**"], # This email es totally fake reply_to=[email]) try: email_to_send.send() return redirect(reverse('contact') + '?ok') except Exception: return redirect(reverse('contact') + '?fail') return render(request, "contact/contact.html", {"form": contact_form})
def general(request): template_name = 'contact/general.html' if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): if request.POST.get('complete') == '1': _notify_sender(form.cleaned_data, request) messages.add_message(request, messages.SUCCESS, 'お問い合わせを承りました。確認のメールを送信しました。') return redirect('home') elif not request.POST.get('complete'): template_name = 'contact/general_confirm.html' else: #ログインしてたら登録情報をセット if request.user.is_authenticated(): u = request.user p = u.myuserprofile form = ContactForm( initial={ 'email': u.email, 'first_name': p.first_name, 'last_name': p.last_name, 'department': p.department, 'company_name': p.company_name, 'tel': p.tel, 'fax': p.fax, 'site_url': p.site_url, }) else: form = ContactForm() return render_to_response(template_name, { 'form': form, }, context_instance=RequestContext(request))
def contactpage(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() # Sending email. subject = form.cleaned_data['subject'] email = [form.cleaned_data['email'], settings.EMAIL_HOST_USER, ] message = form.cleaned_data['message'] send_mail(subject, message, settings.EMAIL_HOST_USER, email, fail_silently=False) url = reverse('contact:message-sent') return HttpResponseRedirect(url) else: form = ContactForm( initial={ 'name': u'Kolo\u017ei Robert', 'email': u'*****@*****.**', 'subject': u'[Django] Test from gmail to eunet.rs subject', 'message': u'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas et nunc id felis condimentum ullamcorper nec a orci. Morbi placerat convallis pharetra. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin volutpat id massa et pulvinar. Etiam est ligula, imperdiet sed sollicitudin vitae, vehicula id nunc. Maecenas at sollicitudin nunc, at fringilla nisi. Duis egestas lorem tristique, suscipit nisi nec, commodo sem. Nulla ac eros nec leo tincidunt bibendum a eget felis. Nunc consectetur enim ligula, vel egestas quam rutrum in.', 'web_site': u'http://www.robertkolozsi.org' } ) context = { 'form': form, } return render_to_response('contact/index.html', context, context_instance=RequestContext(request))
def contact(request): contact_list = Contact.objects.all() displayed_object = contact_list[0] 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 subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] recipients = ['*****@*****.**'] if cc_myself: recipients.append(sender) send_mail(subject, message, sender, recipients) return HttpResponseRedirect('/') # Redirect after POST else: form = ContactForm() # An unbound form return render_to_response('contact/contact.html', { 'displayed_object': displayed_object, 'form': form, }, context_instance=RequestContext(request))
def post(self, request): form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phoneNumber = form.cleaned_data['phoneNumber'] message = form.cleaned_data['message'] contact = Contact( name=name, email=email, phoneNumber=phoneNumber, message=message ) contact.save() subject = 'hassaniprojects.com - Inquiry' from_email = config('DEFAULT_FROM_EMAIL') to_email = [config('EMAIL_PERSONAL')] message = """ name - {} email - {} phoneNumber - {} message - {}""".format( name, email, phoneNumber, message ) _ = send_mail( subject, message, from_email, to_email, fail_silently=config('EMAIL_FAIL_SILENTLY', cast=bool) ) if _ == 1: messages.success( request, "Thank you and I will get back to you as soon as possible." ) elif _ == 0: messages.error( request, "A problem occured while submitting the form. Please feel " "free to send me a direct email to " + config('EMAIL_PERSONAL') ) return redirect('index') else: messages.error( request, "A problem occured while submitting the form. Feel " "free to send me a direct email to " + config('EMAIL_PERSONAL') ) return redirect('index')
def test_contact_form_escaped_tags(admin, rf, mailoutbox): request = rf.request() request.user = admin request.META['REMOTE_ADDR'] = '127.0.0.1' recipient_email = settings.POOTLE_CONTACT_EMAIL specified_subject = "My <tag> subject" subject = "[%s] %s" % (settings.POOTLE_TITLE, specified_subject) data = { 'name': admin.full_name, 'email': admin.email, 'email_subject': specified_subject, 'body': "First <tag> of message.", } form = ContactForm(request=request, data=data) assert form.is_valid() form.save() assert len(mailoutbox) == 1 message = mailoutbox[0] assert message.from_email == settings.DEFAULT_FROM_EMAIL reply_to = u'%s <%s>' % (data['name'], data['email']) assert reply_to == message.extra_headers['Reply-To'] assert [recipient_email] == message.recipients() assert escape(subject) == message.subject assert escape(data['body']) in message.body assert "Your question or comment:" not in message.body
def home(request): songs = Song.objects members = Member.objects infos = Info.objects if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] name = request.POST['name'] subject = str('Anfrage: ' + name) now = datetime.datetime.now() today = now.date() try: contact_mail(from_email, subject, message) except BadHeaderError: return HttpResponse('Invalid header found.') render(request, 'home.html', { 'songs': songs, 'members': members, 'infos': infos, 'form': form }) return render(request, 'home.html', { 'songs': songs, 'members': members, 'infos': infos, 'form': form })
def service_list_by_category_view(request, category): """Shows services for a chosen category. If url doesn't link to existing category, return user to categories list""" template_name = 'services/service-list-by-category.html' if request.method == "POST": contact_form = ContactForm(request.POST) if contact_form.is_valid(): contact_form.save() return redirect(reverse('accounts:profile')) else: if request.user.is_authenticated: initial_data = { "user": request.user, "name": request.user.first_name + " " + request.user.last_name, "email": request.user.email } form = ContactForm(request.POST or None, initial=initial_data) else: form = ContactForm() try: obj = ServiceCategory.objects.get(name=category) queryset = Service.objects.filter(category=obj.pk) context = { "obj": obj, "queryset": queryset, "form": form, } except ServiceCategory.DoesNotExist: messages.error(request, 'No category named <em>' + category + '</em>.') return redirect("services:services_list") return render(request, template_name=template_name, context=context)
def test_sender_missing_but_cc_myself_true(self): form = ContactForm({ "subject": "Bonjour", "cc_myself": True, "message": "Ça va ?" }) self.assertFalse(form.is_valid())
def showPost(request, post_id): post_obj = Post.objects.get(id = int(post_id)) form = ContactForm(request.POST or None, request.FILES or None, post_id = post_obj) if request.method == 'POST' and form.is_valid(): return create_contact(request, form, post_obj) # GET or invalid form sitter_obj = post_obj.author post = post_obj.__dict__ post['species_of_animal'] = Species.objects.all().filter(post = post_id) post['number_of_animal'] = myModule.get_number_of_pet(sitter_obj.user_id) try: Bookmark.objects.get(user = get_user(request), post = post_obj) post['marked'] = True except: post['marked'] = False sitter = sitter_obj.__dict__ sitter['name'] = str(sitter_obj) sitter['score'] = myModule.get_sitter_score(sitter_obj) sitter['photo'] = myModule.get_userimg(sitter_obj) return render(request, 'posting/post_detail.html', { 'post' : post, 'sitter':sitter, 'form':form, } )
def test_invalid_contact_form(self): form = ContactForm({ 'contact_name': 'Christian Plesca', 'message_subject': 'Subject', }) self.assertFalse(form.is_valid())
def home_view(request, *args, **kwargs): if request.method == "GET": pages = Page.objects.filter(show=True).order_by('position') socials = SocialLink.objects.all() projects = Project.objects.filter(is_private=False).order_by('-last_updated') form = ContactForm() context = { "pages": pages, "socials": socials, "projects": projects, "form": form, } if request.session.get('submit_success', None) is not None: context["success"] = request.session.get('submit_success') del request.session['submit_success'] return render(request, "index.html", context) elif request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): request.session['submit_success'] = True form.process() return HttpResponseRedirect('/#contact') else: request.session['submit_success'] = False return HttpResponseRedirect('/#contact')
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): response = requests.post('http://localhost:8000/api/v1/contacts/', request.POST) print('response', response.status_code) if response.status_code == 200: # csrfContext = RequestContext(request) return render( request, 'success.html', { "active_tab": "contact", "request": request }, ) else: return HttpResponse( "Your query could not be submitted. Please try again.") contact_form = ContactForm() # csrfContext = RequestContext(request) return render( request, 'contact.html', { 'form': contact_form, "active_tab": "contact", "request": request }, # csrfContext )
def contact(request): args = {} # If the form is submitted if request.method == 'POST': form = ContactForm(request.POST) # If the data submitted are valid if form.is_valid(): # Get the data from the form name = form.cleaned_data['name'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] recipients = ['*****@*****.**'] # Submit the email send_mail(name, email, message, recipients) # Redirect to thank the user for getting in touch return HttpResponseRedirect(reverse('contact-thanks')) # If the form is not submitted, load the contact form else: form = ContactForm() # If the form is not submitted for any reason, # return any possible errors or display the form args['form'] = form return render(request, 'contact/contact-form.html', args)
def contact_form_required_values(self): form = ContactForm({ "contact_name": "test", "contact_email": "test", "content": "test" }) self.assertTrue(form.is_valid())
def contact(request): next = request.GET.get('next', '/') anti_spam_delay = 10 if hasattr(settings, 'CONTACTS_ANTI_SPAM_DELAY'): anti_spam_delay = settings.CONTACTS_ANTI_SPAM_DELAY if request.method == "POST": contactForm = ContactForm(request.POST) if contactForm.is_valid(): # send mail from smtplib import SMTPException from django.core.mail import send_mail, BadHeaderError key = '%s_cannot_send_email' % request.META.get('REMOTE_ADDR', 'unknown_host') cannot_send_email = cache.get(key) if cannot_send_email: cannot_send_email = cannot_send_email*2 cache.set(key, cannot_send_email) messages.error(request, _('To prevent spamming you cannot send another message so soon, please wait another %s seconds.') % cannot_send_email) else: try: send_mail(contactForm.cleaned_data.get('subject'), contactForm.cleaned_data.get('message'), contactForm.cleaned_data.get('email'), settings.CONTACT_EMAILS) messages.success(request, _('Your message has been sent')) cache.set(key, anti_spam_delay) return HttpResponseRedirect(next) except BadHeaderError: messages.error(request, _('Sorry, we were unable to send your message due to a technical difficulty. Please retry later.')) else: # prefillForm with GET params initial_values = request.GET.copy() if request.user.is_authenticated(): initial_values.update({'name': request.user.get_full_name(), 'email': request.user.email}) contactForm = ContactForm(initial=initial_values) return render_to_response('contact/contact.html', locals(), context_instance=RequestContext(request))
def contact(request): if request.method == 'POST': contact_form = ContactForm(request.POST) if contact_form.is_valid(): name = contact_form.cleaned_data['name'] message = contact_form.cleaned_data['message'] sender = contact_form.cleaned_data['sender'] recipients = ['*****@*****.**'] send_mail(name, message, sender, recipients) contact_form.save() messages.success(request, 'Message sent successfully') return redirect('contact:success') else: messages.error(request, 'Error sending your Message') else: contact_form = ContactForm() context = { "contact_form": contact_form, } template = 'contact/contact.html' return render(request, template, context)
def contact_us(request): latest_contact_text = ContactText.objects.all().order_by('id')[:1] print latest_contact_text if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] message = form.cleaned_data['message'] send_mail( 'EcoCheck SignUp', '%s \n yours %s' % (message,name), email, [settings.CONTACT_MAIL], fail_silently=False ) return render_to_response("contact/contact_success.html", { "name": name, }, context_instance=RequestContext(request)) else: form = ContactForm() return render_to_response("contact/contactus.html", { "form": form, "latest_contact_text":latest_contact_text, }, context_instance=RequestContext(request))
def test_contact_form_with_invalid_data_should_be_invalid_and_have_errors( self ): invalid_data = [ { 'first_name': '', 'last_name': 'P', 'email': '*****@*****.**' }, { 'first_name': 'N', 'last_name': '', 'email': '*****@*****.**' }, { 'first_name': '', 'last_name': '', 'email': '*****@*****.**' }, { 'first_name': '', 'last_name': '', 'email': '' } ] for each in invalid_data: form = ContactForm(data=each) self.assertFalse(form.is_valid()) self.assertTrue(form.errors)
def serve(self, request): from contact.forms import ContactForm form = ContactForm(request.POST) if form.is_valid(): # Clean the data senders_name = form.cleaned_data['your_name'] senders_email = form.cleaned_data['your_email'] message_subject = form.cleaned_data['subject'] message = form.cleaned_data['your_message'] site_name = settings.WAGTAIL_SITE_NAME to_email = settings.CONTACT_EMAIL #Process the form info to get it ready for send_mail subject_line = f"""New message from {site_name} contact form: {message_subject}""" message_body = f"""You have recieved the following message from your website, {site_name}:\n\nSender's Name: {senders_name}\n\n Sender's Email:{senders_email}\n\nSubject:{message_subject}\n\n Message Body: {message}""" # And send # Add a try/except block with errors, including for HTTP header injection! send_mail(subject_line, message_body, senders_email, [to_email]) # create the success url render / template else: form = ContactForm() return render(request, 'contact/contact_page.html', { 'page': self, 'form': form, })
def post(self, request): form = ContactForm(request.POST) bot = Bot.objects.get(number=1) contact = Contact.objects.last() if contact and contact.phone == request.POST.get('phone'): print('errror') if contact and contact.email == request.POST.get('email'): print('errror') else: if form.is_valid(): # Отправляем данные в телеграм url = f'{bot.url}' + 'sendMessage' chat_id = bot.chat_id name = request.POST.get('name') # Поучаем имя title = request.POST.get('title') # Получаем заголовок страницы phone = request.POST.get('phone') # Получаем Телефон contact_url = request.POST.get('url') # Получаем адрес страницы комментария text = f'Заявка на обратную связь \n \n Имя: {name} \n ' \ f'Телефон: {phone} \n \n Страница: \n {title} \n \n Адрес: {contact_url}' if name is None: answer = {'chat_id': chat_id, 'text': 'У нас новый подписчик!'} else: answer = {'chat_id': chat_id, 'text': text} requests.post(url, answer) # Сохраняем форму form.save() return form
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) #Если форма заполнена корректно, сохраняем все введённые пользователем значения if form.is_valid(): subject = form.cleaned_data['subject'] sender = form.cleaned_data['sender'] message = form.cleaned_data['message'] recipients = ['*****@*****.**'] #Если пользователь захотел получить копию себе, добавляем его в список получателей # if copy: # recipients.append(sender) try: send_mail(subject, message, sender, recipients) except BadHeaderError: #Защита от уязвимости return HttpResponse('Invalid header found') #Переходим на другую страницу, если сообщение отправлено return render( request, 'contact/thanks.html', ) else: #Заполняем форму form = ContactForm() #Отправляем форму на страницу return render(request, 'contact/contact.html', { 'form': form, })
class ContactFormTest(TestCase): """ Tests the contact form. Instance variables: val_from_name -- valid from name val_from_email -- valid email address val_to_name -- valid choice for who it's going to val_message -- valid message valid_form -- a valid form """ def setUp(self): """Set up contact test.""" # Set environment variable so that we can get around recaptcha os.environ["RECAPTCHA_TESTING"] = "True" # Make a bunch of valid fields for the valid form self.val_from_name = "AT test val_from_name" self.val_from_email = "*****@*****.**" self.val_to_name = "HO" self.val_message = "This is an automated test from test_valid_data" # Make a dictionary of all the valid fields which can be used later self.valid_dict = { "from_name": self.val_from_name, "from_email": self.val_from_email, "to_name": self.val_to_name, "message": self.val_message, "g-recaptcha-response": "PASSED", } # Create the valid form self.valid_form = ContactForm(self.valid_dict) def test_valid_data_equals_valid_form(self): """ Tests that form is valid. """ self.assertTrue(self.valid_form.is_valid()) def test_data_goes_into_object(self): """ Tests all fields go into object model correctly. """ saved_comment = self.valid_form.save() self.assertEqual(saved_comment.from_name, self.val_from_name) self.assertEqual(saved_comment.from_email, self.val_from_email) self.assertEqual(saved_comment.to_name, self.val_to_name) self.assertEqual(saved_comment.message, self.val_message) # TODO: This probable belongs ina model test. contact_queryset = Contact.objects.filter(message__exact=self.val_message) first_object = contact_queryset[0] self.assertEqual(first_object.from_name, self.val_from_name) def tearDown(self): """ Unset everything that needs to be unset before next test. """ os.environ["RECAPTCHA_TESTING"] = "False"
def index(request): if request.method == "POST": contact_form = ContactForm(request.POST) if contact_form.is_valid(): pass else: contact_form = ContactForm() return render_to_response('contact/index.html', {'contact_form': contact_form}, context_instance=RequestContext(request))
def index(request, template_name='content/index.html'): page_title = 'Contact DanuGroup.org' form=ContactForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/contact/thankyou.html') else: return render_to_response(template_name, {'form': ContactForm()}, context_instance=RequestContext(request))
def contact(request): form = ContactForm(request.POST or None) if form.is_valid(): form.send() return HttpResponseRedirect(reverse('contact')) return render_to_response('contact/contact.html', {'form':form}, context_instance=RequestContext(request))
def post(self, request, *args, **kwargs): form_data = ContactSerializer(self.request.DATA).data form = ContactForm(form_data) if form.is_valid(): form.send_email() return Response({}, status=200) else: return Response({"errors": form.errors}, status=422)
def contact(request): if request.method=="POST": form = ContactForm(request.POST) if form.is_valid(): return HttpResponse("<p>Thank You!</p>") else: form = ContactForm() return render(request, "contact.html", {"form":form})
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(request, "contact_form.html", {"form": form})
def test_invalid_data(self): data = { 'name': 'Ade Oluwa', 'email': '[email protected]!', 'phone_number': '08033445566', 'comment': 'Keep up the good work!' } form = ContactForm(data) self.assertFalse(form.is_valid()) self.assertTrue(form['email'].errors, [u'Enter a valid e-mail address.'])
def contact_add(request): if request.method == 'GET': contactForm = ContactForm() return render(request, 'contact/contact.html', dictionary={'ContactForm': contactForm}) else: contactForm = ContactForm(request=request) if contactForm.is_valid(): #create new contact and redirect to contact form contact/11334533/ print 'success form was valid' return render(request, 'contact/contact.html', dictionary={'ContactForm': contactForm})
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", "email": "*****@*****.**"}) return render_to_response("contact_form.html", {"form": form})
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data print 'Sending mail from ' + request.POST.get('email', '*****@*****.**') + ' to [email protected] with subject "'+ request.POST['subject'] + '" with message "' + request.POST['message'] + '"...' return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm(initial={ 'subject': 'I love your site!' }) return render(request, 'contact_form.html', { 'form': form })
def contact_page(request): form = ContactForm() completed = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.send_email() completed = True context = {'form':form, 'completed': completed} return render(request, 'contact/contact.html', context)
def test_success(self): data = { 'name': 'Ade Oluwa', 'email': '*****@*****.**', 'phone_number': '08033445566', 'comment': 'Keep up the good work!' } form = ContactForm(data) self.assertTrue(form.is_valid()) c = form.save() self.assertEqual(repr(c), '<Contact: Ade Oluwa : Keep up the good work!>')
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): cd = form.cleaned_data return render_to_response('contact/thanks.html',{'subject':cd['subject']}) #send_mail(cd['subject'],cd['message'],cd.get('email','*****@*****.**'),['*****@*****.**'],) #return HttpResponseRedirect('thanks/',{'subject':cd['subject']}) else: form = ContactForm(initial={'subject':'Test site'}) return render_to_response('contact/contact_form.html',{'form':form}, context_instance=RequestContext(request))
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('e_mail', '*****@*****.**'), ['*****@*****.**'],) return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm(initial = {'subject' : 'F**k!!!'}) return render_to_response('contact_form.html', {'form' : form})