def contact_form(request): # If the request method is POST, it means that the form has been submitted # and we need to validate it. if request.method == 'POST': # Create a ContactForm instance with the submitted data form = ContactForm(request.POST) # is_valid validates a form and returns True if it is valid and # False if it is invalid. if form.is_valid(): # The form is valid and you could save it to a database # by creating a model object and populating the # data from the form object, but here we are just # rendering a success template page. cd = form.cleaned_data send_mail(cd['subject'], cd['message'], cd.get('email','*****@*****.**'), ['*****@*****.**'], fail_silently=False, ) return render(request, 'contact_form/success.html') # This means that the request is a GET request. So we need to # create an instance of the ContactForm class and render it in # the template else: form = ContactForm() # Render the contact form template with a ContactForm instance. If the # form was submitted and the data found to be invalid, the template will # be rendered with the entered data and error messages. Otherwise an empty # form will be rendered. Check the comments in the contact_form.html template # to understand how this is done. return render(request, 'contact_form/contact_form.html', {'form':form})
def ContactFormProcessor(request, context_dictionary): if request.method == 'POST': if 'contact' in request.POST: # create a form instance and populate it with data from the request: contact_form = ContactForm(request.POST) # check whether it's valid: if contact_form.is_valid(): first_name = contact_form.cleaned_data['first_name'] last_name = contact_form.cleaned_data['last_name'] address = contact_form.cleaned_data['address'] zipcode = contact_form.cleaned_data['zipcode'] phone = contact_form.cleaned_data['phone'] sender = contact_form.cleaned_data['email'] subject = contact_form.cleaned_data['subject'] subject = subject + '-' + first_name + ' ' + last_name message = contact_form.cleaned_data['message'] recipients = [site_settings_processor(request)['site_email'],] fullemail = first_name + " " + last_name + " " + "<" + sender + ">" send_mail(subject, message, fullemail, recipients, fail_silently=False) context_dictionary['first_name'] = contact_form.cleaned_data['first_name'] else: context_dictionary['form_errors'], context_dictionary['contact_form'] = True, contact_form else: pass else: contact_form = ContactForm() context_dictionary['contact_form'] = contact_form
def contact_admin(request): #check if form was posted if request.method == 'POST': #create a form instance and populate it with data from the request form = ContactForm(request.POST) #check whether user data is valid if form.is_valid(): #send mail subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] from_email = form.cleaned_data['from_email'] try: send_mail(subject, message, from_email, [ADMIN_EMAIL]) except Exception: message = u'Во время отправки письма случилась непредсказуемая ошибка.Попробуйте воспользоваться позже.' else: message = u'Сообщение успешно отправлено!' #redirect to same contact page with success message return HttpResponseRedirect( u'%s?status_message=%s' % (reverse('contact_admin'), message)) else: form = ContactForm() return render(request, 'contact_admin/form.html', {'form': form})
def test_invalid_form(self): data = dict(sender_name='test', sender_email='*****@*****.**', subject='', message='') form = ContactForm(data=data) self.assertFalse(form.is_valid())
def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sender_name = request.POST.get('name') sender_email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') email = EmailMessage( 'Message From Website.', message, sender_email, [ '*****@*****.**', '*****@*****.**', '*****@*****.**' ], headers={'Reply-To': sender_email}) email.send() # if sender_name and sender_email and subject and message: # try: # send_mail(subject, message, sender_email, ['*****@*****.**'], # fail_silently=False, # ) # except BadHeaderError: # return HttpResponse("Bad Header") return render(request, 'contact_form/mail_received.html', {}) form = ContactForm() return render(request, 'contact_form/contact_form.html', {'form': form})
def contact(request): c = {} c.update(csrf(request)) contactFormSet = modelformset_factory(Contact) contactCategory = list(ContactCategory.objects.filter(is_active=True)[:1]) if contactCategory: contactCategory = contactCategory[0] c.update({'contactCatetory': contactCategory}) if request.method == 'POST': contact = ContactForm(request.POST) if contact.is_valid(): contact = contact.save() current_site = Site.objects.get_current() subject = Template(contactCategory.msg_subject).render(Context({'site': current_site})) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message = Template(contactCategory.msg_body).render(Context( {'contact': contact, 'message': contact.message, 'site': current_site})); # if contactCategory.msg_html_body: # message = Template(contactCategory.msg_html_body).render(Context( # {'contact': contact.name, # 'email': contact.email, # 'message': contact.message, # 'site': current_site })); send_html_mail(subject, message, message, settings.DEFAULT_FROM_EMAIL, [email.strip() for email in contactCategory.recipients.split(',')]) # send mail to contact person to inform them the email has been sent reply_subject = Template(contactCategory.reply_subject).render(Context({})) reply_message = Template(contactCategory.reply_body).render(Context({'contact': contact.name})) send_html_mail(reply_subject, reply_message, reply_message, settings.DEFAULT_FROM_EMAIL, [contact.email]) if request.is_ajax(): return HttpResponse(json.dumps({'success': True}), mimetype='application/json') else: return render(request, 'contact_form/message_sent.html') else: return HttpResponse(json.dumps({'success': False, 'errors': contact.errors}), mimetype='application/json') else: storage = messages.get_messages(request) storage.used = False c['contact'] = ContactForm() return render(request, "contact_form/contact.html", c)
def test_invalid_form(self): data = dict( sender_name='test', sender_email='*****@*****.**', subject='', message='' ) form = ContactForm(data=data) self.assertFalse(form.is_valid())
def test_valid_form(self): data = dict( sender_name='test', sender_email='*****@*****.**', subject=self.subject_foo.id, message='test message from user foo', captcha='', ) form = ContactForm(data=data) self.assertTrue(form.is_valid())
def contact(request): if request.method == 'POST': form = ContactForm(request.POST, request.FILES, request=request) if form.is_valid(): form.save() return HttpResponseRedirect('%s?success' % request.path) else: form = ContactForm(request=request) return render_to_response('contact_form/contact_form.html', { 'form': form, 'success': 'success' in request.GET, }, context_instance=RequestContext(request))
def test_no_sites(self): """ Sites integration works with or without installed contrib.sites. """ with self.modify_settings( INSTALLED_APPS={"remove": ["django.contrib.sites"]}): form = ContactForm(request=self.request(), data=self.valid_data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(1, len(mail.outbox))
def test_send(self): """ Valid form can and does in fact send email. """ form = ContactForm(request=self.request(), data=self.valid_data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(1, len(mail.outbox)) message = mail.outbox[0] self.assertTrue(self.valid_data["body"] in message.body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, message.from_email) self.assertEqual(form.recipient_list, message.recipients())
def home_page(request): form = ContactForm(request.POST or None) # Get last three projects projects = (ProjectItem.objects.all())[:3] # get about info try: about_page = (About.objects.all())[0] about = about_page.get_cleaned_data() except: about = {} # Check if it form redirection and send response if(request.method == "POST"): response = manage_form(request, form, send_email) return HttpResponse(json.dumps(response), content_type="application/json") context = { "form": form, "projects": projects, "about": about.get("about", ""), "about_img": about.get("about_img", ""), "developer_skills": about.get("developer_skills", ""), "designer_skills": about.get("designer_skills", ""), } tags = [] # Get tags for i in range(len(projects)): tags.append(projects[i].tags.all()) context["tags"] = tags return render(request, "home_page/home_page.html", context)
def faq(request): questions = Question.objects.active() form = ContactForm(request=request) # form_class = form if request.method == 'POST': form = ContactForm(data=request.POST, files=request.FILES, request=request) if form.is_valid(): form.save() messages.info(request, _("New question succesfully sent."), fail_silently=True) return HttpResponseRedirect(reverse('faq')) template = "faq.html" data = {'items': questions, 'form': form, 'section': 'faq',} return render_to_response(template, data, context_instance=RequestContext(request))
def test_no_sites(self): """ Sites integration works with or without installed contrib.sites. """ with self.modify_settings( INSTALLED_APPS={ 'remove': ['django.contrib.sites'], }): form = ContactForm(request=self.request(), data=self.valid_data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(1, len(mail.outbox))
def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['view'] = 'home' context['top_mixtures'] = Mixture.published.top_rates() context['top_categories'] = Category.final.top_content() context['form'] = ContactForm(request=self.request) return context
def get_context_data(self, **kwargs): context = super(MixtureDetailView, self).get_context_data(**kwargs) try: if 'slug' in self.kwargs: # this is backward compatibility mixture = Mixture.published.get( Q(slug_en=self.kwargs['slug']) | Q(slug_es=self.kwargs['slug'])) else: # normal mixture detail request mixture = Mixture.published.get(pk=self.kwargs['pk']) except Mixture.DoesNotExist: raise Http404() context['object'] = mixture currency_code = self.request.GET.get( 'c', settings.CURRENCY_DEFAULT).upper() currency = Currency.objects.get(code=currency_code) context['currency'] = currency context['category_tree'] = Category.tree(mixture.category) context['form'] = ContactForm(request=self.request) return context
def blog_home(request, template="blog/blog_index_page.html"): """ This is the blog home view. """ # Gather all blogs to display. blog_queryset = BlogPage.objects.all() print("I'm still here!") form = ContactForm() if form._post_clean() is valid: # Now do something with the submitted form content. print("THE FORM IS VALID...") else: messages.info("There was a problem in submitting the form.") return response(template, request, {'blogpages': blog_queryset})
def test_recipient_list(self): """ Passing recipient_list when instantiating ContactForm properly overrides the list of recipients. """ recipient_list = ["*****@*****.**"] form = ContactForm(request=self.request(), data=self.valid_data, recipient_list=recipient_list) self.assertTrue(form.is_valid()) form.save() self.assertEqual(1, len(mail.outbox)) message = mail.outbox[0] self.assertEqual(recipient_list, message.recipients())
def test_recipient_list(self): """ Passing recipient_list when instantiating ContactForm properly overrides the list of recipients. """ recipient_list = ['*****@*****.**'] form = ContactForm(request=self.request(), data=self.valid_data, recipient_list=recipient_list) self.assertTrue(form.is_valid()) form.save() self.assertEqual(1, len(mail.outbox)) message = mail.outbox[0] self.assertEqual(recipient_list, message.recipients())
def test_send(self): """ Valid form can and does in fact send email. """ form = ContactForm(request=self.request(), data=self.valid_data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(1, len(mail.outbox)) message = mail.outbox[0] self.assertTrue(self.valid_data['body'] in message.body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, message.from_email) self.assertEqual(form.recipient_list, message.recipients())
def test_valid_data_required(self): """ Can't try to build the message dict unless data is valid. """ data = {"name": "Test", "body": "Test message"} form = ContactForm(request=self.request(), data=data) self.assertRaises(ValueError, form.get_message_dict) self.assertRaises(ValueError, form.get_context)
def test_valid_data_required(self): """ Can't try to build the message dict unless data is valid. """ request = RequestFactory().request() data = {'name': 'Test', 'body': 'Test message'} form = ContactForm(request=request, data=data) self.assertRaises(ValueError, form.get_message_dict)
def test_no_sites(self): """ Sites integration works with or without installed contrib.sites. """ old_installed = Site._meta.installed Site._meta.installed = False request = RequestFactory().request() data = {'name': 'Test', 'email': '*****@*****.**', 'body': 'Test message'} form = ContactForm(request=request, data=data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(1, len(mail.outbox)) Site._meta.installed = old_installed
def test_send(self): """ Valid form can and does in fact send email. """ request = RequestFactory().request() data = {'name': 'Test', 'email': '*****@*****.**', 'body': 'Test message'} form = ContactForm(request=request, data=data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(1, len(mail.outbox)) message = mail.outbox[0] self.assertEqual([data['email']], message.recipients()) self.assertTrue(data['body'] in message.body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, message.from_email)
def contact_form(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your request submitted successfully') else: messages.error(request, 'Please fix the errors and re-submit') else: form = ContactForm() return render(request, "contact-form.html", {"form": form})
def test_send(self): """ Valid data through the view results in a successful send. """ contact_url = reverse("contact_form") data = { "name": "Test", "email": "*****@*****.**", "body": "Test message" } response = self.client.post(contact_url, data=data) self.assertRedirects(response, reverse("contact_form_sent")) self.assertEqual(1, len(mail.outbox)) message = mail.outbox[0] self.assertTrue(data["body"] in message.body) self.assertEqual(settings.DEFAULT_FROM_EMAIL, message.from_email) form = ContactForm(request=RequestFactory().request) self.assertEqual(form.recipient_list, message.recipients())
def contact_processor(request): return {'contact_form': ContactForm(request=request)}
def __init__(self, *args, **kwargs): ContactForm.__init__(self, *args, **kwargs) self.fields.keyOrder = ['name', 'email', 'subject', 'accept_terms', 'body']