Reputation: 964
I am learning celery with django. I am trying to create a simple addition project with django and celery. I created a simple webapp with django. in the index.html template, I have a form with 2 input fields. The first input field takes the x value
(the first number for addition). The second input field takes y value
(the second number for addition). When the form is submitted, I want the celery task to run. The django project name is core and the app name is mainapp
The celery task is as follows
mainapp/tasks.py
from celery import Celery
from celery.schedules import crontab
from celery import shared_task
@shared_task
def add_num(x, y):
return x+y
core/celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
app = Celery('core')
app.conf.timezone = 'UTC'
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()
mainapp/views.py
from django.shortcuts import render
from . import tasks
# Create your views here.
def index(request):
if request.method == 'POST':
x = request.POST['x']
y = request.POST['y']
print(x, y)
add_num.delay(x, y)
return render(request, 'index.html')
return render(request, 'index.html')
I have rabbitmq running in the background with the following command
brew services start rabbitmq
celery is running in a separate terminal window with the following command
celery -A core worker -B -l INFO
When I submit the form I get the following error.
NameError: name 'add_num' is not defined
I guess I am not importing the tasks into views.py properly.
Upvotes: 1
Views: 3772
Reputation: 11665
Incorrect import
change below line
from . import tasks
to
from .tasks import add_num
Upvotes: 3