本文整理汇总了Python中contact.forms.ContactForm类的典型用法代码示例。如果您正苦于以下问题:Python ContactForm类的具体用法?Python ContactForm怎么用?Python ContactForm使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ContactForm类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_contact_form
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': '[email protected]',
'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': '[email protected]',
'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())
示例2: contact
def contact(db):
"""
Our contact-us form, basically, present a form if it's a GET request,
validate and process the form if it's a POST request. Filthy but works.
"""
form = ContactForm(request.POST, nocaptcha={'ip_address': '127.0.0.1'})
if request.method == 'POST' and form.validate():
# process the form, captcha is valid.
message_text = "Contact Email: {email}\n\n {contact_text}".format(
email=form.email.data,
contact_text=form.contact_text.data
)
# put together a gmail client for sending messages
gmail_client = GMail(settings.ADMIN_EMAIL,
settings.ADMIN_EMAIL_PASSWORD)
message = Message('[xqzes] Contact Form',
to=settings.ADMIN_EMAIL,
text=message_text)
gmail_client.send(message)
return redirect("/contact/?contacted=True")
return template(
'contact',
form=form,
contacted=strtobool(request.GET.get('contacted', 'false'))
)
示例3: contactpage
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'[email protected]',
'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))
示例4: contact
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))
示例5: contact
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 = ['[email protected]']
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))
示例6: general
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))
示例7: test_contact_form_with_invalid_data_should_be_invalid_and_have_errors
def test_contact_form_with_invalid_data_should_be_invalid_and_have_errors(
self
):
invalid_data = [
{
'first_name': '',
'last_name': 'P',
'email': '[email protected]'
},
{
'first_name': 'N',
'last_name': '',
'email': '[email protected]'
},
{
'first_name': '',
'last_name': '',
'email': '[email protected]'
},
{
'first_name': '',
'last_name': '',
'email': ''
}
]
for each in invalid_data:
form = ContactForm(data=each)
self.assertFalse(form.is_valid())
self.assertTrue(form.errors)
示例8: contact
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})
示例9: contact_us
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))
示例10: contact
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))
示例11: test_contact_form_escaped_tags
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
示例12: edit
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))
示例13: home
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),
)
示例14: contact
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 = ['[email protected]']
# 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)
示例15: ContactFormTest
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 = "[email protected]"
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"