Format email message in Django - python

I'm trying to send email message in one of my views and would like to format the body of the message, such that it shows in different lines.
This is a snippet code in views.py:
body = "Patient Name: " + patient_name + \
"Contact: " + phone + \
"Doctor Requested: Dr. " + doctor.name + \
"Preference: " + preference
email = EmailMessage('New Appointment Request', body, to=['ex#gmail.com'])
email.send()
The email is shown like this:
Patient Name: AfrojackContact: 6567892Doctor Requested: Dr. IrenaPreference: Afternoon
How do I make it show like this:
Patient Name: Afrojack
Contact: 6567892
Doctor Requested: Dr. Irena
Preference: Afternoon

I suggest to use the django template system to do that.
You could do:
```
from django.template import loader, Context
def send_templated_email(subject, email_template_name, context_dict, recipients):
template = loader.get_template(email_template_name)
context = Context(context_dict)
email = EmailMessage(subject, body, to=recipients)
email.send()
```
The template will look like: this could for example be in the file myapp/templates/myapp/email/doctor_appointment.email:
```
Patient Name: {{patient_name}}
Contact: {{contact_number}}
Doctor Requested: {{doctor_name}}
Preference: {{preference}}
```
and you will use it like
```
context_email = {"patient_name" : patient_name,
"contact_number" : phone,
"doctor_name": doctor.name,
"preference" : preference}
send_templated_email("New Appointment Request",
"myapp/templates/myapp/email/doctor_appointment.email",
context_email,
['ex#gmail.com'])
```
This is very powerfull, because you can style all the email in the way you want,
and you re-use the same function over and over, just need to create new template
and pass appropriate context/subject and recipietns

you should add '\n' for newlines.
or you could try this:
body = '''Patient Name: {}
Contact: {}
Doctor Requested: Dr. {}
Preference: {}'''.format(patient_name, phone, doctor.name, preference)
or, if you are using python >= 3.6:
body = f'''Patient Name: {patient_name}
Contact: {phone}
Doctor Requested: Dr. {doctor.name}
Preference: {preference}'''

You are going right but you just missed a letter n
body = "Patient Name: " + patient_name + "\n"
+ "Contact: " + phone + "\n"
+ "Doctor Requested: Dr. " + doctor.name + "\n"
+ "Preference: " + preference
This will add new line after each and every line and most probably solve your problem.

this should do the trick for breakline:
\n

Related

Django Foreign Key Related Objects Not Saving Changes, Cannot Edit

I have two models, Movie and Review. Review has a foreign key field related to Movie. I have been trying to edit the Review objects associated with an instance of Movie.
models.py
class Movie(models.Model):
title = models.CharField(max_length=160)
class Review(models.Model):
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='reviews')
author = models.CharField(max_length=150)
active = models.BooleanField(default=True)
views.py
# Create and save movie object
movie = Movie(title="Nightcrawler")
movie.save()
# Create and save two review objects
review1 = Review(movie=movie, author="John", active=True)
review2 = Review(movie=movie, author="Rob", active=False)
review1.save()
review2.save()
print("Before: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.")
active_reviews = movie.reviews.filter(active=True)
print("There are " + str(len(active_reviews)) + " active reviews.")
movie.reviews.set(active_reviews)
movie.reviews.first().author = "Abby"
# Try and save both objects just for good measure.
# Not sure if it is necessary to do this. Does not
# seem to work anyway
movie.reviews.first().save()
movie.save()
print("After: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.")
print("Author of the first review is: " + str(movie.reviews.first().author))
The output of the views.py code is as follows:
Before: Nightcrawler has 2 reviews.
There are 1 active reviews.
After: Nightcrawler has 2 reviews.
Author of the first review is: John
I want and expected the changes made to movies.reviews to be saved, but the output reveals that neither the set() method or changing the author value actually alters the Movie instance. Why are none of these edits being preserved?
Interestingly, the line movies.reviews.first().delete() does seem to actually remove the first review. I am curious why this works and the other changes do not.
Thank you for your time!
If you want to manipulate the object, you should store it in a variable first
movie = Movie(title="Nightcrawler")
movie.save()
# Create and save two review objects
review1 = Review(movie=movie, author="John", active=True)
review2 = Review(movie=movie, author="Rob", active=False)
review1.save()
review2.save()
print("Before: " + movie.title + " has " + str(len(movie.reviews.all())) + " reviews.")
active_reviews = movie.reviews.filter(active=True).all()
print("There are " + str(len(active_reviews)) + " active reviews.")
movie.reviews.clear()
movie.reviews.set(active_reviews)
first_review = movie.reviews.first()
first_review.author = "Abby"
first_review.save()
movie.save()
It's not being saved because the object you updated is not the same with the object you saved because you ran another query by calling first() again.
If you intend to only keep the "active" reviews, you can use remove instead to remove inactive reviews.
movie.reviews.remove(*movie.reviews.filter(active=False))
set does not have any effect here because the active_reivews you passed as parameter is already linked or already set. If you want to stick with set, do a clear first.

Zapier Action Code: Python will not run with input_data variable

I am using Zapier to catch a webhook and use that info for an API post. The action code runs perfectly fine with "4111111111111111" in place of Ccnum in doSale. But when I use the input_data variable and place it in doSale it errors.
Zapier Input Variable:
Zapier Error:
Python code:
import pycurl
import urllib
import urlparse
import StringIO
class gwapi():
def __init__(self):
self.login= dict()
self.order = dict()
self.billing = dict()
self.shipping = dict()
self.responses = dict()
def setLogin(self,username,password):
self.login['password'] = password
self.login['username'] = username
def setOrder(self, orderid, orderdescription, tax, shipping, ponumber,ipadress):
self.order['orderid'] = orderid;
self.order['orderdescription'] = orderdescription
self.order['shipping'] = '{0:.2f}'.format(float(shipping))
self.order['ipaddress'] = ipadress
self.order['tax'] = '{0:.2f}'.format(float(tax))
self.order['ponumber'] = ponumber
def setBilling(self,
firstname,
lastname,
company,
address1,
address2,
city,
state,
zip,
country,
phone,
fax,
email,
website):
self.billing['firstname'] = firstname
self.billing['lastname'] = lastname
self.billing['company'] = company
self.billing['address1'] = address1
self.billing['address2'] = address2
self.billing['city'] = city
self.billing['state'] = state
self.billing['zip'] = zip
self.billing['country'] = country
self.billing['phone'] = phone
self.billing['fax'] = fax
self.billing['email'] = email
self.billing['website'] = website
def setShipping(self,firstname,
lastname,
company,
address1,
address2,
city,
state,
zipcode,
country,
email):
self.shipping['firstname'] = firstname
self.shipping['lastname'] = lastname
self.shipping['company'] = company
self.shipping['address1'] = address1
self.shipping['address2'] = address2
self.shipping['city'] = city
self.shipping['state'] = state
self.shipping['zip'] = zipcode
self.shipping['country'] = country
self.shipping['email'] = email
def doSale(self,amount, ccnumber, ccexp, cvv=''):
query = ""
# Login Information
query = query + "username=" + urllib.quote(self.login['username']) + "&"
query += "password=" + urllib.quote(self.login['password']) + "&"
# Sales Information
query += "ccnumber=" + urllib.quote(ccnumber) + "&"
query += "ccexp=" + urllib.quote(ccexp) + "&"
query += "amount=" + urllib.quote('{0:.2f}'.format(float(amount))) + "&"
if (cvv!=''):
query += "cvv=" + urllib.quote(cvv) + "&"
# Order Information
for key,value in self.order.iteritems():
query += key +"=" + urllib.quote(str(value)) + "&"
# Billing Information
for key,value in self.billing.iteritems():
query += key +"=" + urllib.quote(str(value)) + "&"
# Shipping Information
for key,value in self.shipping.iteritems():
query += key +"=" + urllib.quote(str(value)) + "&"
query += "type=sale"
return self.doPost(query)
def doPost(self,query):
responseIO = StringIO.StringIO()
curlObj = pycurl.Curl()
curlObj.setopt(pycurl.POST,1)
curlObj.setopt(pycurl.CONNECTTIMEOUT,30)
curlObj.setopt(pycurl.TIMEOUT,30)
curlObj.setopt(pycurl.HEADER,0)
curlObj.setopt(pycurl.SSL_VERIFYPEER,0)
curlObj.setopt(pycurl.WRITEFUNCTION,responseIO.write);
curlObj.setopt(pycurl.URL,"https://secure.merchantonegateway.com/api/transact.php")
curlObj.setopt(pycurl.POSTFIELDS,query)
curlObj.perform()
data = responseIO.getvalue()
temp = urlparse.parse_qs(data)
for key,value in temp.iteritems():
self.responses[key] = value[0]
return self.responses['response']
# NOTE: your username and password should replace the ones below
Ccnum = input_data['Ccnum'] #this variable I would like to use in
#the gw.doSale below
gw = gwapi()
gw.setLogin("demo", "password");
gw.setBilling("John","Smith","Acme, Inc.","123 Main St","Suite 200", "Beverly Hills",
"CA","90210","US","555-555-5555","555-555-5556","support#example.com",
"www.example.com")
r = gw.doSale("5.00",Ccnum,"1212",'999')
print gw.responses['response']
if (int(gw.responses['response']) == 1) :
print "Approved"
elif (int(gw.responses['response']) == 2) :
print "Declined"
elif (int(gw.responses['response']) == 3) :
print "Error"
Towards the end is where the problems are. How can I pass the variables from Zapier into the python code?
David here, from the Zapier Platform team. A few things.
First, I think your issue is the one described here. Namely, I believe input_data's values are unicode. So you'll want to call str(input_data['Ccnum']) instead.
Alternatively, if you want to use Requests, it's also supported and is a lot less finicky.
All that said, I would be remiss if I didn't mention that everything in Zapier code steps gets logged in plain text internally. For that reason, I'd strongly recommend against putting credit card numbers, your password for this service, and any other sensitive data through a Code step. A private server that you control is a much safer option.
​Let me know if you've got any other questions!

Python - creating same sender email/sender in Random email/conversation generator

I'm super new to Python and just trying my hand at a random email generator.
I'm just using json files with datasets in them, so there may be a better way to do this.
I can get the script to work no problems, but I need some advice on something. I want the senders email to be the same as the sign off name.
I.E. david_jones#hotmail etc comes from Regards, David Jones. At the moment i've got it generating a separate random email, and separate sign off name. I need to link the two. Everything else is ok at the moment.
Can anyone help me with a better way to do this?
Code:
import json
import random
f = open("C:/Users/*/Desktop/Email.txt", "a")
sentfrom = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Send.json').read())
send = sentfrom [random.randint(0,4)]
carboncopy = "CC:"
receiver = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/To.json').read())
to = receiver[random.randint(0,4)]
datesent = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Date.json').read())
date = datesent[random.randint(0,4)]
subjects = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Subject.json').read())
subject = subjects[random.randint(0,4)]
greetings = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Greeting.json').read())
greeting= greetings[random.randint(0,4)]
firstsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent1.json').read())
sent1 = firstsentence[random.randint(0,4)]
secondsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent2.json').read())
sent2 = secondsentence[random.randint(0,4)]
thirdsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent3.json').read())
sent3 = thirdsentence[random.randint(0,4)]
fourthsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent4.json').read())
sent4 = fourthsentence[random.randint(0,4)]
farewell = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Goodbye.json').read())
goodbye = farewell[random.randint(0,4)]
regards = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sender.json').read())
salutation = regards[random.randint(0,4)]
conversation = send +'\n'+ to +'\n'+ carboncopy +'\n'+ date +'\n'+ subject +'\n'+ '\n' + greeting +', \n'+ '\n' + sent1 +'\n'+ '\n' + sent2 +'\n'+'\n'+ sent3 +'\n'+'\n'+ sent4 +'\n'+'\n'+ goodbye +'\n'+'\n'+ salutation
f.write(conversation)
f.close()
Thanks in advance,
Buzz
Assuming that regards is what contains the sign off name..
You want to first get rid of the sign off name, instead of 'Regards, John Doe', Have all of them be 'Regards', 'Best', 'Thanks!' etc. maybe just create a list instead of reading it from json:
regards = ['Regards,', 'Best,', 'Thanks!' ...]
Assuming everyone's format in email is the same, i.e. john_doe#whatever.com, you can get the name from this:
my_name = to.split('#')[0].replace('_', ' ').title()
# my_name will be 'John Doe'
And then add my_name to the conversation after salutation.

Get multiline string from Python variables

I have the following piece of code to get name and launch time for each instance:
for instance in instances:
instance_name = instance.name
launch_time = instance.launch_time
As result i want to get a variable with the list like:
instance_name: launch_time
instance_name: launch_time
...
i.e
Name: server1; Launch time: 2 days, 7:33:46.319073
Name: server2: Launch time: 4 days, 6:33:46.319073
...
and then use it for email notification in another multi-line string.
I've done it with:
result = []
result.append({'name':instance_name, 'launch_uptime':uptime })
but i don't like these quotes, i want a good formatted text
You can do like this:
multi_line = ''
for instance in instances:
instance_name = instance.name
launch_time = instance.launch_time
multi_line += 'Name: ' + instance_name +'; Launch time: ' + launch_time + '\n'
print(multi_line)

Print multiple lines in one statement without leading spaces [duplicate]

This question already has answers here:
How can I print multiple things (fixed text and/or variable values) on the same line, all at once?
(13 answers)
Closed 9 months ago.
So for my first project it is a simple program that prints your name class you are in and what high school you went to. The one thing that is messing me up is for one of them I have to use one print() statement for all this and I need to format it so that each piece of information is on a different line.
What I want for the format:
first_name, last_name
course_id, course_name, email
school
But what I get is
first_name, last_name
course_id, course_name, email
school
How do I remove the space?
My code is as follows:
first_name = 'Daniel'
last_name = 'Rust'
course_id = 'Csci 160'
course_name = 'Computer Science 160'
email = 'blah#gmail.com'
school= 'Red River Highschool'
#variables printed for B
print(first_name, last_name, '\n', course_id, course_name, email, '\n', school, '\n')
print inserts a space between each argument. You can disable this by adding , sep='' after the last '\n', but then there won't be any spaces between first_name and last_name or between course_id and course_name, etc. You could then go on to insert , ' ' manually where you need it in the print statement, but by that point it might be simpler to just give print a single argument formed by concatenating the strings together with explicit spaces:
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name
+ ' ' email + '\n' + school + '\n')
As mentioned here, you can use the sep='' argument to the print() function. That will let you set the separator between printed values (which is a space by default) to whatever you want, including an empty string. You'll have to remember to add spaces between the values that you do want separated. E.g.,
print(first_name, ' ', last_name, '\n', course_id, [...], sep='')
There's a better way to do this, involving the format() method on strings, but your professor is probably saving that one for the next lesson so I won't cover it in detail now. Follow the link to the Python docs, and read the section on Format String Syntax, if you want more details. I'll just show you an example of what your code would look like using format():
print("{} {}\n{} {} {}\n{}".format(first_name, last_name, course_id, course_name, email, school))
Note no \n at the end, since print() automatically adds a newline unless you tell it otherwise.
I recommend reading through str.format() to print your information.
The spaces in your output come from the fact that you've called the print function, passing a list of strings, instead of passing the print function a single string.
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name + ' ' + email + '\n' + school)
yields
Daniel Rust
Csci 160 Computer Science 160 blah#gmail.com
Red River Highschool
Just don't add space in your code
print(first_name, last_name, '\n',course_id, course_name, email, '\n', school, '\n')
There are a number of ways to do so.
First can be str.format() as
print ('{} {}\n{} {} {}\n{}'.format(first_name, last_name, course_id, course_name, email, school))
Second can be
print (first_name, ' ', last_name, '\n',course_id, ' ', course_name, ' ', email, '\n',school, sep = '')
And the third can be
print (first_name + ' ' + last_name + '\n' + str(course_id) + ' ' + course_name + ' ' + email + '\n' + school)
Simple multiline print in python using f-string,
first_name = 'Daniel'
last_name = 'Rust'
course_id = 'Csci 160'
course_name = 'Computer Science 160'
email = 'blah#gmail.com'
school= 'Red River Highschool'
#variables printed for B
print(first_name, last_name, '\n', course_id, course_name, email, '\n', school, '\n')
print(f'''
{first_name}, {last_name}
{course_id}, {course_name}, {email}
{school}''')
Daniel Rust
Csci 160 Computer Science 160 blah#gmail.com
Red River Highschool
Daniel, Rust
Csci 160, Computer Science 160, blah#gmail.com
Red River Highschool
[Program finished]
How to print several lines by using one print statement and how to add new line?
pi = 3.14159 # approximate
diameter = 3
radius = diameter/2
area = pi * radius * radius
circumference = 2 * pi * radius
print("{}\n{}\n{}\n".format(area,radius,circumference))
output::
7.068577499999999
1.5
9.424769999999999
the above you will get corrcet answer for this code.

Categories