import celery import weasyprint import pytils from io import BytesIO from django.conf import settings from django.template.loader import render_to_string, get_template from django.core.mail import EmailMessage, EmailMultiAlternatives from cart.models import Order @celery.task def send_user_order_notification(order_id, request): """ Sending Email of order creating """ order = Order.objects.get(id=order_id) verb_price = pytils.numeral.in_words(round(order.total_price)) verb_cur = pytils.numeral.choose_plural(round(order.total_price), ("рубль", "рубля", "рублей")) subject = 'Заказ № {}'.format(order.id) message = 'Уважаемый, {}, номер Вашего заказа {}. \ Пожалуйста, совершите платеж по поручению в приложении к этому письму в течение 14 дней.'.format( order.customer_name, order.id) mail_send = EmailMessage(subject, message, 'admin@myshop.ru', [order.customer_email]) # html = render_to_string('orders:AdminOrderPDF', args=[order_id]) html = render_to_string('orders/pdf.html', {**settings.PAY_REQUISITES, 'order': order, 'verb_cur': verb_cur, 'verb_price': verb_price}) rendered_html = html.encode(encoding="UTF-8") out = BytesIO() weasyprint.HTML(string=rendered_html).write_pdf(out, stylesheets=[ weasyprint.CSS(settings.STATIC_ROOT + 'css/build.css')]) order_invoice_name = 'Order_' + order.order_code weasyprint.HTML(string=rendered_html, base_url=request.build_absolute_uri()).write_pdf(order_invoice_name, stylesheets=[weasyprint.CSS( settings.STATIC_ROOT + '/css/build.css')]) mail_send.attach('order_{}.pdf'.format(order_id), out.getvalue(), 'application/pdf') mail_send.send() return mail_send @celery.task def send_admin_order_notification(context): body = get_template('emails/html/admin_order_request.html') body_text = get_template('emails/txt/admin_order_request.txt') email = EmailMultiAlternatives( context['email']['subject'], body_text.render(context['email']), context['from_email'], context['recipients'] ) email.attach_alternative(body.render(context['email']), 'text/html') try: email.send() except Exception as e: return False return True