Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach generated CSV file to email and send with Django

Tags:

I need to generate a csv file based on the queryset result, attach the resulting file to an email as attachment and send. As you can see i need to iterate over the assigned_leads and write it to a file so i thought yield would do the trick. Now when i run the code i receive the email with attachment with below message instead of the rows i expect. If i use return i get the one row from the queryset result.

<generator object data at 0x7f5e508d93c0>  def send_lead_reminder(request):     usercompany = Listing.objects.filter(submitted_by=request.user)     assigned_leads = lead.objects.filter(assigned_to__in=usercompany).distinct()      def data():         csvfile=StringIO.StringIO()         csvwriter =csv.writer(csvfile)         for leads in assigned_leads:             csvwriter.writerow([leads.business_name, leads.first_name, leads.last_name, leads.email, leads.phone_number,leads.address, leads.city, leads.state, leads.zipcode, leads.submission_date, leads.time_frame, leads.comments])              yield csvfile.getvalue()     message = EmailMessage("Hello","Your Leads","[email protected]",["[email protected]"])     message.attach('invoice.csv', data(), 'text/csv')     #message.to="[email protected]"     message.send()     return HttpResponseRedirect('/') 
like image 481
shaytac Avatar asked Jul 11 '13 03:07

shaytac


People also ask

Can I use CSV as database in django?

Django uses python's built-in csv library to create Dynamic CSV (Comma Separated values) file. We can use this library into our project's view file. Lets see an example, here we have a django project to that we are implementing this feature. A view function getfile() is created.


1 Answers

Is there a particular reason you're using an additional function at all? Just build your csv in memory - you can't avoid that if you're attaching it to email - and send that.

assigned_leads = lead.objects.filter(assigned_to__in=usercompany).distinct() csvfile = StringIO.StringIO() csvwriter = csv.writer(csvfile) for leads in assigned_leads:     csvwriter.writerow([leads.business_name, leads.first_name, leads.last_name, leads.email, leads.phone_number,leads.address, leads.city, leads.state, leads.zipcode, leads.submission_date, leads.time_frame, leads.comments]) message = EmailMessage("Hello","Your Leads","[email protected]",["[email protected]"]) message.attach('invoice.csv', csvfile.getvalue(), 'text/csv') 
like image 127
Peter DeGlopper Avatar answered Sep 17 '22 13:09

Peter DeGlopper