How I Created a Simple Contact Page in Python Django

5/5 - (1 vote)

High-Level Approach

Creating a contact page in Django involves creating a new app, adding it to the project settings, and defining a model for the contact form. You then create a form for the model, a view to handle form submission and display, and a URL for the view. Finally, you create templates for the form and a success page, and run the server to view your contact form.

Here’s a step-by-step guide:

Step 1: Create a new Django app

First, you need to create a new Django app. In your terminal, navigate to your Django project directory and run the following command:

python manage.py startapp contact

This will create a new Django app named ‘contact‘.

Step 2: Add the app to your project settings

Open your Django project’s settings file (usually settings.py) and add your new app to the INSTALLED_APPS list:

INSTALLED_APPS = [
    ...
    'contact',
    ...
]

Step 3: Create a model for the contact form

In the models.py file of your new app, create a model for the contact form. This model will define the fields of the form.

Here’s a basic example:

from django.db import models

class Contact(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    message = models.TextField()

Step 4: Create a form for the model

In the same directory, create a new file named forms.py and define a form for your model:

from django import forms
from .models import Contact

class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        fields = ['name', 'email', 'message']

Step 5: Create a view for the form

In the views.py file of your app, create a view for your form:

from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()
            return render(request, 'contact/success.html')
    else:
        form = ContactForm()
    return render(request, 'contact/contact.html', {'form': form})

This view will display the contact form when the page is visited, and it will save the form data when the form is submitted.

Step 6: Create a URL for the view

In the urls.py file of your app, create a URL for your view:

from django.urls import path
from .views import contact_view

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

Step 7: Create templates for the form and the success page

In your app’s templates directory (you might need to create it), create a new directory named ‘contact’ and inside it, create two HTML files: contact.html and success.html. The contact.html file should contain the form, and the success.html file should contain a message that will be displayed when the form is successfully submitted.

Step 8: Run the server

Finally, run your server with python manage.py runserver and visit http://localhost:8000/contact/ to see your contact form.

Remember to replace ‘contact‘ with the actual name of your app if it’s different. Also, this is a very basic example. In a real-world application, you would probably want to add more features, like sending an email when the form is submitted, validating the form data, etc.

Example: Portfolio Website Django

We will create a contact page so anyone who wants to pass information or suggestions can reach us. We have already created a contact page while building a portfolio website using Django. Please go through that tutorial for more explanation because we will do exactly what we did there.

Add this Contact class to your models.py file:

from datetime import datetime

class Contact(models.Model):
    name = models.CharField(max_length=50)
    subject = models.CharField(max_length=200)
    email = models.EmailField()
    submitted_on = models.DateTimeField(default=datetime.now)
    message = models.TextField()

    def __str__(self):
        return self.name

Perform migrations and proceed to create a ContactForm class in your forms.py file.

class ContactForm(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Name'}))
    email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}))
    subject = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Subject'}))
    message = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Message'}))

    class Meta:
        model = Contact
        fields = ('name', 'email', 'subject', 'message')

For the admin interface, let’s create the class in admin.py file.

class ContactAdmin(admin.ModelAdmin):
    list_display = ('name', 'email', 'subject', 'message')

admin.site.register(Contact, ContactAdmin)

Be sure to import all the necessary modules. For the view function:

from django.views.generic import CreateView
from django.contrib.messages.views import SuccessMessageMixin
from .forms import ContactForm
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse_lazy

class ContactView(SuccessMessageMixin, CreateView):
    form_class = ContactForm
    success_url = reverse_lazy('index')
    template_name = 'contact.html'
    success_message = 'Your message was submitted successfully'

    def form_invalid(self, form):
        message.error(self.request, 'An unknown error has occurred!')
        return HttpResponseRedirect('')

let’s now create the template using the name we specified in the ContactView class.

{% extends 'base.html' %}

{% block content %}

<div class="col-md-8 card mb-4 mt-3">
      <h1 align="center">Contact Form</h1>
      <hr>
      <p>We want to hear from you. Please fill out this contact form for suggestions.</p>
      <hr>
      <br>
      <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary btn-lg">Submit</button>
     </form>
 </div>
{% endblock %}

You are free to use the Django crispy forms as demonstrated in that project. For the endpoint, it will be like this:

path('contact', ContactView.as_view(), name='contact'),