sending email

120 views
Skip to first unread message

sum abiut

unread,
Jan 19, 2015, 10:02:45 PM1/19/15
to django...@googlegroups.com
Hi,
I am trying to send an email to several users once a form is submit. I have done the view.py to update the database once the form is submitted and is working fine. what i want to accomplish when the form is submitted is to update the database and at the same time send out email when a user click on the Authorized leave button.

here is the step i want to do:

 Inline image 1

1) user click on the check box and this form below appears


Inline image 2
 2) the user then fill up the form and click on authorized leave button. the form will stored the information into the database. which i have already done it. what i wanted to do next is to also send a emails when the authorized leave button is click. is it possible to send emails and also save data to database when the authorized leave button is click. i want to send email to the Test User which have his email address store in the database.

template.html
<form action ="" method="post">{%csrf_token%}
<table>
{{form.as_table}}
</table>
<br>
<input type="submit" name="submit" value="Authorized Leave" > 


</form>

please point me to the right direction.

Cheers,  

Collin Anderson

unread,
Jan 21, 2015, 11:03:02 PM1/21/15
to django...@googlegroups.com
Hi,

Yes, this is possible. Something like:

from django.core.mail import send_mail

def authorized_leave(request):
    form
= MyForm()
   
if request.method == 'POST':
        form
= MyForm(request.POST)
       
if form.is_valid():
            obj
= form.save()
            send_mail
('Subject here', 'Here is the message.', 'fr...@example.com', ['t...@example.com'])
           
return redirect('/done/')
   
return render(request, 'template.html', {form: 'form'})

Collin

sum abiut

unread,
Jan 21, 2015, 11:29:51 PM1/21/15
to django...@googlegroups.com
Thanks,
I am trying to send email to the users that their email address is stored in the database on the auth_user table. can someone please point me to the right direction.

Cheers,


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3df19a0c-2afc-4e17-b527-83d38a639611%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



Collin Anderson

unread,
Jan 22, 2015, 9:18:30 PM1/22/15
to django...@googlegroups.com
Hi,

Just query the users you want.

to_emails = [u.email for u in User.objects.filter(username__in=['person1', 'person2', 'person3'])]
send_mail('Subject here', 'Here is the message.', from_email_address, to_emails)

Collin

sum abiut

unread,
Jan 25, 2015, 11:53:12 PM1/25/15
to django...@googlegroups.com
Hi Collin,
Thank you very much for your help. its works perfectly.
The next thing i want to do is to send an email to a specific user that i select on a table. when an authorized user select a user to approve his or her leave i want an email to be send to the user. so basically when i click on the checkbox on the Test User form the table below. i should get a form to approve the leave as below. now when i click on authorized Leave button an email should be send to the test user. please point me to right direction.
 Inline image 1

Inline image 2

Cheers,


For more options, visit https://groups.google.com/d/optout.



-

Collin Anderson

unread,
Jan 27, 2015, 3:18:24 PM1/27/15
to django...@googlegroups.com
Hi,

You should be able to figure out which box is checked from form.cleaned_data.

Collin

sum abiut

unread,
Jan 27, 2015, 11:56:03 PM1/27/15
to django...@googlegroups.com
Can someone please guide me here. i am kinda lost, the other part is ok just the email part i am really lost, please help

here is my view.py the email part is not working

def coporateservices_authorized_Leave(request, id):
    if request.method == 'POST':
        a=newleave.objects.get(id=id)
        form = coporateservices_authoriseleave(request.POST, instance=a)
        if form.is_valid():
           form.save()
           to_emails = [u.email for u in User.objects.filter(id__in=[a.'id'])]
           send_mail("RBV Leave Application Email Testing", "Your Leave have been approved",
          "RBV eLeave <Rbv_eLeave_System>", [to_emails])
        return render_to_response('thankyou.html')
    else:
        a=newleave.objects.get(id=id)
        form =  coporateservices_authoriseleave(instance=a)
    return render_to_response('coporate_services_leave_approvial.html', {'form': form}, context_instance=RequestContext(request))

cheers,





James Schneider

unread,
Jan 29, 2015, 3:01:17 AM1/29/15
to django...@googlegroups.com

Couple things. 

I think the return statement for thankyou.html needs to get kicked in a tab, otherwise the form will show successful every time the form is submitted, even if it had errors.If there are errors, it will also skip your email code, but still show as successful.

This line is very confusing:

to_emails = [u.email for u in User.objects.filter(id__in=[a.'id'])]

I don't even think a.'id' is valid syntax. More to the point, your variable 'a' is populated a few lines earlier using a get() queryset, which means it can only contain one item. That would render the list comprehension statement (bad syntax aside) completely useless, since you would only ever have a single element. That also makes the id__in filter unnecessary as well. 

Which leads to another question, are you expecting your User objects to contain the same ID as your newleave objects (for example, User.id == newleave.id). That is indicated by the User.objects query you are making, and I believe you may be incorrect there as well.

Without having seen the model, I'm guessing you want the list of administrative users that are tied to a particular leave, your query line would probably look something like this:

to_emails = [*a.admins.all()]

Also, in your send_mail call, you are encapsulating to_emails inside of another list, like this send_mail(..., [to_emails]). Something tells me you probably don't need to do that, since to_emails is already a list, but I could be wrong there as well.

-James






sum abiut

unread,
Feb 2, 2015, 12:52:03 AM2/2/15
to django...@googlegroups.com
Thank your for your response and clarification. i am not sure why i am getting this error. i want to be able to send an email to the user that i have selected. Thanks in advance for your help

I am getting the error:
'newleave' object has no attribute 'admins'

here is my model.py and view.py

model.py

class newleave(models.Model):
first_name = models.CharField(max_length=45)
last_name =models.CharField(max_length=45)
department=models.CharField(max_length =45)
position=models.CharField(max_length =45)
leave_type =models.CharField(max_length=45)
specify_details=models.TextField(default="")
start_date =models.DateField(null=True)
end_date=models.DateField(null=True)
total_working_days=models.IntegerField(null=True)
department_head_authorization =models.CharField(max_length=45, default ="")
authorized_by=models.CharField(max_length=45, default ="")
remarks=models.TextField()
authorization_date =models.DateField(null=True)
corporate_services_authorization =models.CharField(max_length=45)
authorized_by1=models.CharField(max_length=45)
remarks1=models.TextField(default ="")
authoriztaion1_date =models.DateField(null=True)
total_Leave_Left =models.IntegerField(default=20)
username =models.ForeignKey(User, default =1)



view.py


def coporateservices_authorized_Leave(request, id):
if request.method == 'POST':
a=newleave.objects.get(id=id)
form = coporateservices_authoriseleave(request.POST, instance=a)
if form.is_valid():
form.save()
    to_emails = [a.admins.all()]

send_mail("RBV Leave Application Email Testing", "Your Leave have been approved",
"RBV eLeave <Rbv_eLeave_System>", [to_emails])
return render_to_response('thankyou.html')
else:
a=newleave.objects.get(id=id)
form = coporateservices_authoriseleave(instance=a)
return render_to_response('coporate_services_leave_approvial.html', {'form': form}, context_instance=RequestContext(request))

 

Cheers



monoBOT

unread,
Feb 2, 2015, 4:45:35 AM2/2/15
to django...@googlegroups.com

2015-02-02 6:51 GMT+01:00 sum abiut <sua...@gmail.com>:

to_emails = [a.admins.all()]

​You are asking for item admins here:


to_emails = [a.admins.all()]



--
monoBOT
Visite mi sitio(Visit my site): monobotsoft.es/blog/

sum abiut

unread,
Feb 2, 2015, 10:39:28 PM2/2/15
to django...@googlegroups.com
Hi James,

if you have a look at my view.py code below. i am trying to send email to a selected user that i have select to update that particular user using a form. The updated part is working fine now, i can update the particular row that i have selected. what i want to do next is to email that particular user that his data has been updated. i am still very confuse about the email part.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.



-

sum abiut

unread,
Feb 3, 2015, 12:04:16 AM2/3/15
to django...@googlegroups.com
Hi James,
I manage to fixe my email issue. Basically what i am trying to do here is to get the app to send an email to the a leave applicant when his/her leave is approved by the department director and at the same time update the data on the databases.

Here is my working view.py code for future referencing.


def coporateservices_authorized_Leave(request, id):
    if request.method == 'POST':
        a=newleave.objects.get(id=id)
        form = coporateservices_authoriseleave(request.POST, instance=a)
        if form.is_valid():
         form.save()
        to_emails = [u.email for u in User.objects.filter(username__in=[a.username])]
        send_mail("RBV Leave Application Email Testing", "Your Leave Application have been approved by"+" "+a.authorized_by1,
        "RBV eLeave <Rbv_eLeave_System>", to_emails)

        return render_to_response('thankyou.html')
    else:
        a=newleave.objects.get(id=id)
        form =  coporateservices_authoriseleave(instance=a)
        return render_to_response('coporate_services_leave_approvial.html', {'form': form}, context_instance=RequestContext(request))

once again thank you very much for your help.


 Cheers.



James Schneider

unread,
Feb 3, 2015, 1:38:23 AM2/3/15
to django...@googlegroups.com

Oh, I see what you are trying to do. It looks like you are running needless queries though.

Your newleave model has this: 

    username  =models.ForeignKey(User,  default =1)

That's an FK to User, which means this line in your view:

    to_emails = [u.email for u in User.objects.filter(username__in=[a.username])]

is only querying for information that you already have, and trying to use list comprehension for a query that should only ever return a single result. The line above should be shortened to the following:

    to_emails = [ a.username.email ]

I was previously assuming that you wanted to email the admins of the leave, hence the funny query with a.admins, etc (which was a pure guess since I hadn't seen the model). Now I can see that you want to email the user that is directly attached to the leave. To make it even more slick, in addition to the change above, you can also add a select_related('username') to the original newleave query so that you'll only run a single query, which is much more efficient, like this:


def coporateservices_authorized_Leave(request, id):
    if request.method == 'POST':

        a=newleave.objects.select_related('username').get(id=id)
        form = coporateservices_authoriseleave(request.POST, instance=a)

        if form.is_valid(): 
            form.save()
            to_emails = [ a.username.email ]


            send_mail("RBV Leave Application Email Testing", "Your Leave Application have been approved by"+" "+a.authorized_by1,
            "RBV eLeave <Rbv_eLeave_System>", to_emails)
            return render_to_response('thankyou.html')
    else:
        a=newleave.objects.get(id=id)
    form =  coporateservices_authoriseleave(instance=a)
    return render_to_response('coporate_services_leave_approvial.html', {'form': form}, context_instance=RequestContext(request))


Other musings:

Try to be more consistent with your naming conventions for your classes and function/view names. For example, I would have named your newleave class as NewLeave, using CamelCase (aka CapCase) for all class names. Check out Python's PEP8 for more style guidelines: https://www.python.org/dev/peps/pep-0008/

I would also recommend using string token replacement to fill in strings using data from variables rather than concatenating them using the + notation. For example: 

"Your Leave Application have been approved by {}".format(a.authorized_by1)

It is more conventional and will make it easier to start passing in strings for translation later, if needed.


Glad you got it working though.

-James


sum abiut

unread,
Feb 3, 2015, 2:15:09 AM2/3/15
to django...@googlegroups.com
Hi James,
Thanks very much for clearing things up. I appreciate every bit of information and help from you. I have learn a lot since i have join this mailing list. I am pretty much new to Django and i appreciate every help and support that you guys are giving. It helps heaps. i will follow your direction.

Cheers

Reply all
Reply to author
Forward
0 new messages