Basic Django-RQ Example

This is part 3 in a 4 part series looking at how to do background/async tasks in Django. See this post for more details.

This is based on my notes from the following GitHub repository:

Basic Django-RQ Example

You could git clone this repository to get it working but I recommend following these manual steps so you understand what’s required to get a basic Django-RQ example up and running.

  • Before you start, you’ll need a Redis server. If you don’t have one the easiest way is through Docker with the following command:
docker run --name my-redis-server -d -p redis
  • Create a virtual environment using the method of your choice, I like to use the following command:
python3.8 -m venv .venv && source .venv/bin/activate && pip install --upgrade pip wheel setuptools > /dev/null
  • Create the requirements.txt file to install the packages required:
  • Activate your virtual environment and install the requirements in the requirements.txt file:
pip install -r requirements.txt
  • Create your Django project:
django-admin startproject djangorq_project .
  • Open the file and add Django Q to the list of installed apps to complete installation.
  • Open the project file and add the Django-RQ URLs to complete installation.
urlpatterns = [
    path("django-rq/", include("django_rq.urls")),
  • Add the Django-RQ configuration in the file:
# Django-RQ Configuration
    "default": {"HOST": "localhost", "PORT": 6379, "DB": 0, "DEFAULT_TIMEOUT": 360,},
  • That’s the base project configuration complete, run the database migrations and create a superuser:
python migrate
python createsuperuser
  • Add a new app, we’ll make a basic contact form app that stores messages in our database and sends an email to the site owner:
django-admin startapp contact_form
  • Add some email configuration to the file. I use Amazon SES but substitute with our own SMTP settings.
# Email
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = ""  # add your own settings here
EMAIL_PORT = ""  # add your own settings here
EMAIL_HOST_USER = ""  # add your own settings here
EMAIL_HOST_PASSWORD = ""  # add your own settings here
EMAIL_USE_TLS = True  # add your own settings here
DEFAULT_FROM_EMAIL = "[email protected]"  # your email address
  • While you’re in the settings, add your new app to the INSTALLED_APPS section:
  • Create a model to store the messages sent from the website in contact_form >
from django.db import models

class ContactForm(models.Model):
    email = models.EmailField()
    name = models.CharField(max_length=64)
    subject = models.CharField(max_length=64)
    message = models.TextField()
    created_on = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "contactform"
        verbose_name = "contact form message"
        verbose_name_plural = "contact form messages"

    def __str__(self):
  • Expose the model in the Admin site with contact_form >
from django.contrib import admin

from .models import ContactForm

class ContactFormAdmin(admin.ModelAdmin):
    list_display = ("email", "name", "subject", "created_on"), ContactFormAdmin)
  • Create a contact form in contact_form > (you’ll need to create this file):
from django.forms import ModelForm

from .models import ContactForm

class ContactFormModelForm(ModelForm):
    class Meta:
        model = ContactForm
        fields = ["name", "email", "subject", "message"]
  • Create the Django-RQ task to send an email in contact_form > (you’ll need to create this file):
from django.core.mail import send_mail, BadHeaderError
from djangorq_project.settings import DEFAULT_FROM_EMAIL
from django_rq import job

import logging

logger = logging.getLogger(__name__)

def send_email_task(to, subject, message):"from={DEFAULT_FROM_EMAIL}, {to=}, {subject=}, {message=}")
    try:"About to send_mail")
        send_mail(subject, message, DEFAULT_FROM_EMAIL, [DEFAULT_FROM_EMAIL])
    except BadHeaderError:"BadHeaderError")
    except Exception as e:
  • Create a basic template to use: contact_form > templates > contact_form > contact_form.html (you’ll need to create these folders and file):
<!doctype html>
<html lang="en">
        <meta charset="utf-8">
        <title>Contact Form</title>
        <h2>Contact Form</h2>
        <form method="post" action="">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="Send Message">
  • Create a view in contact_form >
from django.views.generic import FormView

from .forms import ContactFormModelForm
from .tasks import send_email_task

class ContactFormView(FormView):
    form_class = ContactFormModelForm
    template_name = "contact_form/contact_form.html"
    success_url = "/"

    def form_valid(self, form):

        return super().form_valid(form)

    def send_email(self, valid_data):
        email = valid_data["email"]
        subject = "Contact form sent from website"
        message = (
            f"You have received a contact form.\n"
            f"Email: {valid_data['email']}\n"
            f"Name: {valid_data['name']}\n"
            f"Subject: {valid_data['subject']}\n"
        send_email_task.delay(email, subject, message,)
  • Create a URLs configuration in contact_form > (you’ll need to create this file):
from django.urls import path

from .views import ContactFormView

app_name = "contact_form"
urlpatterns = [
    path("", ContactFormView.as_view(), name="contact_form"),
  • Update the project URLs to reference these new URLs in djangorq_project >
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("", include("contact_form.urls")),
  • Create and apply the database migrations for the new model
python makemigrations
python migrate
  • Now you need to launch the Django test server:
python runserver
  • Then in a second terminal window, navigate to your project directory, activate the virtual environment again, and then launch the Django-RQ rqworker process – it should print out some debug information and then a Lisenting on default... message to indicate it has connected to Redis successfully and is waiting for tasks:
python rqworker default
  • Browse to and you should see a contact form. Try sending a message to see if it works.

  • Switch back to your terminal windows with the Django-RQ process and you’ll see some updates. It can take several seconds to send the email, but that was all done by the rqworker process and didn’t affect the page loading time after submitting the form.

  • After sending a message, log in to the admin site ( and take a look at the contact form model we created.

Hopefully that worked for you and gives you something to build upon.

2 replies on “Basic Django-RQ Example”

Hello. Great async info. I found a couple errors in the article. The git repo does not have these errors.
`from djangoq_project.settings import DEFAULT_FROM_EMAIL`
should be
`from djangorq_project.settings import DEFAULT_FROM_EMAIL`
missing `from django_rq import job` and the `@job` decorator
`def send_email_task(self, to, subject, message):`
should be
`def send_email_task(to, subject, message):`

Thanks for the feedback Rob. I’ve fixed the errors you pointed out, much appreciated. These were copied from the file in the Git repo so I also updated that file too.


Leave a Reply

Your email address will not be published.