# orders/tasks.py
from celery import shared_task
from django.core.mail import send_mail
from .models import Order
@shared_task
def order_created(order_id):
order = Order.objects.get(id=order_id)
subject = f'Order nr.{order.id}'
message = f'Dear {order.first_name},\n\n You have successfully placed an order. Your order ID is {order.id}.'
mail_sent = send_mail(subject, message, '[email protected]', [order.email])
return mail_sent
# orders/views.py
from django.shortcuts import render
from .models import OrderItem
from .forms import OrderCreateForm
from cart.cart import Cart
from .tasks import order_created
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save()
for item in cart:
OrderItem.objects.create(
order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity']
)
cart.clear()
order_created.delay(order.id)
return render(request, 'orders/order/created.html', {'order': order})
else:
form = OrderCreateForm()
return render(request, 'orders/order/create.html', {'form': form})
我在我的项目中导入了celery,并想创建一个异步任务, 阅读完 celery 文档后,我认为我做的一切都是正确的,而且仍然 延迟方法不存在
Django==5.0.1 芹菜==5.3.6
根据 Celery 签名文档,
您可以通过以下方式同步运行任务:
order_created.s(order.id).apply()
或异步方式:
order_created.s(order.id).apply_async()