Contact Form with Django and SQLite

When I first started working with Django, building forms that interact seamlessly with databases was always a key part of my projects. One of the most common features I’ve implemented is a contact form, a simple yet powerful way for users to get in touch. If you’re looking to create a contact form using Django and SQLite, you’re in the right place.

In this tutorial, I’ll walk you through the entire process, from setting up your Django project to creating a contact form that saves submissions directly into an SQLite database. I’ll share practical tips and code examples that I’ve used in real projects, making it easy for you to follow along and build your own.

Steps to Use Django with SQLite for a Contact Form

Django’s built-in ORM (Object-Relational Mapping) makes working with databases like SQLite straightforward. SQLite is lightweight, serverless, and perfect for small to medium projects or prototypes, especially if you’re targeting users in the USA who want a quick, reliable contact form without complex setup.

Read Python Django: Get Admin Password

Step 1: Set Up Your Django Project

If you haven’t already installed Django, start by running:

pip install django

Next, create a new Django project and app:

django-admin startproject contactproject
cd contactproject
python manage.py startapp contactapp

Add your new app to INSTALLED_APPS in contactproject/settings.py:

INSTALLED_APPS = [
    # existing apps
    'contactapp',
]

Step 2: Define the Contact Model

The contact form submissions will be saved in the database. For this, we need to create a model in contactapp/models.py:

from django.db import models

class Contact(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    subject = models.CharField(max_length=200)
    message = models.TextField()
    submitted_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} - {self.subject}"

Run migrations to create the corresponding table in SQLite:

python manage.py makemigrations
python manage.py migrate

Step 3: Create a Contact Form Using Django Forms

Django’s form system makes validation and rendering easy. In contactapp/forms.py, add:

from django import forms
from .models import Contact

class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        fields = ['name', 'email', 'subject', 'message']
        widgets = {
            'name': forms.TextInput(attrs={'placeholder': 'Your full name'}),
            'email': forms.EmailInput(attrs={'placeholder': 'Your email address'}),
            'subject': forms.TextInput(attrs={'placeholder': 'Subject'}),
            'message': forms.Textarea(attrs={'placeholder': 'Your message'}),
        }

Step 4: Build Views to Handle Form Display and Submission

In contactapp/views.py, create a view to handle GET and POST requests:

from django.shortcuts import render, redirect
from .forms import ContactForm

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()  # Save data to SQLite
            return redirect('contact_success')
    else:
        form = ContactForm()
    return render(request, 'contactapp/contact.html', {'form': form})

def contact_success(request):
    return render(request, 'contactapp/success.html')

Step 5: Set Up URLs

Create contactapp/urls.py:

from django.urls import path
from .views import contact_view, contact_success

urlpatterns = [
    path('', contact_view, name='contact'),
    path('success/', contact_success, name='contact_success'),
]

Include these URLs in the main project’s urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('contact/', include('contactapp.urls')),
]

Check out Upload Image File in Django

Step 6: Create Templates for the Form and Success Page

Create a folder contactapp/templates/contactapp/ and add two HTML files:

contact.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Contact Us</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; }
        label { display: block; margin-top: 15px; }
        input, textarea { width: 100%; padding: 8px; margin-top: 5px; }
        button { margin-top: 20px; padding: 10px 20px; }
    </style>
</head>
<body>
    <h1>Contact Us</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Send</button>
    </form>
</body>
</html>

success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Message Sent</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; text-align: center; }
    </style>
</head>
<body>
    <h1>Thank You!</h1>
    <p>Your message has been sent successfully. We will get back to you shortly.</p>
    <a href="{% url 'contact' %}">Send Another Message</a>
</body>
</html>

Step 7: Run Your Django Project

Finally, start the development server:

python manage.py runserver

Open your browser and navigate to http://127.0.0.1:8000/contact/. You should see your contact form ready to use.

You can refer to the screenshot below to see the output.

django contact form with database
contact form in Django

Read Django vs ReactJS

Alternative Method: Use Django’s Built-in Email Backend

If you want your contact form to send emails directly instead of just saving to the database, you can configure Django’s email settings and modify the view to send an email upon submission.

Here’s a quick example of how to do that inside your contact_view:

from django.core.mail import send_mail
from django.conf import settings

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            contact = form.save(commit=False)
            # Send email
            send_mail(
                contact.subject,
                contact.message,
                contact.email,
                [settings.DEFAULT_FROM_EMAIL],
                fail_silently=False,
            )
            contact.save()
            return redirect('contact_success')
    else:
        form = ContactForm()
    return render(request, 'contactapp/contact.html', {'form': form})

Make sure to configure your email backend in settings.py with SMTP details or use the console backend for testing:

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEFAULT_FROM_EMAIL = 'your_email@example.com'

This method is useful if you want immediate notifications without checking the database.

Building a contact form with Django and SQLite is simple and flexible. Whether you want to store submissions or send emails, Django’s robust tools make the process smooth. I hope this guide helps you create a contact form tailored to your needs quickly.

If you want to expand this further, consider adding CAPTCHA for spam protection or integrating with third-party email services for better deliverability.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.