I am leraning Django using django 3 by example. I want to launch asynchronous task with celery. I set the settings but the task will not execute. i'm using rabbit mq as broker and i'm using windows. Here is my code:
celery.py
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Onlineshop.settings')
app = Celery('Onlineshop')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
init .py
from .celery import app as celery_app
__all__ = ('celery_app',)
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):
"""Task to send an e-mail notification when order is successfully created."""
order = Order.objects.get(id=order_id)
subject = f'Order nr. {order.id}'
message = f'Dear {order.first_name},\n\n' \
f' You have successfully placed an order.' \
f'Your order ID is {order.id}'
mail_sent = send_mail(subject, message, 'admin@onlineshop.com', [order.email])
return mail_sent
views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import OrderItem
from .forms import OrderCreateForm
from cart.cart import Cart
from .tasks import order_created
# Create your views here.
@login_required
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
user = request.user
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
order.user = user
order.save()
for item in cart:
OrderItem.objects.create(order=order, product=item['product'], price=item['price'],
quantity=item['quantity'])
context = {
'order': order,
}
# clear the cart
cart.clear()
# launch asynchronous task
order_created.delay(order.id)
return render(request, 'order/created.html', context)
else:
form = OrderCreateForm()
context = {'cart': cart,
'form': form,
}
return render(request, 'order/create.html', context)
Here is the problem in my view i called order_created function but the task will not execute and there in no email in my console. my email settings are correct because other emails in my app works. I use flower to monitor celery and in flower panel it shows that the tasks are executing but there is no email. i would be happy if any body can help
Okay by running the command Rabbitmq-server restart and also to get celery to connect to the server by running the command Celery -A app_name worker --loglevel=info.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.