How to Build a Contact Form in Django

Django Code
Views
URLs
Models
Admin
Forms
html
        

from django.shortcuts import render, redirect
from .forms import ContactForm
from django.core.mail import send_mail

def contact_view(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            form.save()  # Save to database
            # Optionally, send an email
            send_mail(
                form.cleaned_data['subject'],
                form.cleaned_data['message'],
                form.cleaned_data['email'],  # From email
                ['admin@example.com'],  # To email
            )
            return redirect('contact_view')  # Redirect to success page after submitting
    else:
        form = ContactForm()

    return render(request, 'contact.html', {'form': form})

        
    
        


from django.urls import path
from . import views

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

        
    
        

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()

    def __str__(self):
        return f'{self.name} - {self.email}'

        
    
        

from django.contrib import admin
from .models import Contact

class ContactAdmin(admin.ModelAdmin):
    list_display = ('name', 'email', 'subject', 'message')  # To display these fields in the admin list view
    search_fields = ('name', 'email', 'subject')  # To add a search bar for these fields
    list_filter = ('email',)  # To filter contacts by email

admin.site.register(Contact, ContactAdmin)
 
    
    
        


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={'class': 'form-control', 'placeholder': 'Your Name'}),
            'email': forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Your Email'}),
            'subject': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Subject'}),
            'message': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Your Message'}),
        }

    
    
        


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Us</title>
</head>
<body>
    <div class="container">
        <h1>Contact Us</h1>
        <form method="post" action="{% url 'contact' %}">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Send</button>
        </form>
    </div>
</body>
</html>
    
    

Django is a powerful web framework that simplifies building web applications with Python. One of the fundamental features you might need is a contact form, which allows users to send messages directly from your website. In this blog post, we’ll guide you through the process of creating a contact form with Django, covering all the essential components and steps involved.

Understanding the Contact Form Components

Creating a contact form involves several key components, each serving a specific purpose. Here’s a high-level overview of these components and their roles:

  1. Model: The model defines the structure of the data we want to collect. For a contact form, we need fields to capture the user’s name, email, subject, and message. This model will store the contact information in the database.
  2. Form: The form handles user input and validation. It ensures that the data entered by users is correctly formatted and meets the required criteria. The form also renders the HTML for the contact fields, providing an interface for users to fill out.
  3. View: The view manages the logic for displaying the form and processing form submissions. It determines how the form should be presented and what actions to take when the form is submitted. For instance, it might save the form data to the database or send an email notification.
  4. URL Configuration: URLs map the web address to the view that handles it. This configuration ensures that when users navigate to the contact page, the correct view is called to render the form and handle submissions.
  5. Admin Interface: Django’s admin interface allows you to manage and view the data collected through the contact form. This feature provides a convenient way to review and manage contact messages directly from the Django admin panel.
  6. HTML Template: The HTML template defines how the contact form is displayed to users. It includes the form fields and any additional elements, such as success messages or error notifications.

Steps to Create the Contact Form

  1. Define the Model: Start by creating a model to represent the contact form data. This model will include fields for the user’s name, email, subject, and message. It’s essential to structure this model according to the information you want to collect.
  2. Create the Form: Next, define a form that mirrors the model. This form will handle user input and ensure that it is validated correctly. It will also provide the necessary HTML elements for users to fill out the contact form.
  3. Configure the View: The view will control how the form is displayed and processed. It will handle both displaying the form to users and processing the form data when it is submitted. This may include saving the data to the database and sending email notifications.
  4. Set Up URLs: Configure the URLs to map the contact page to the appropriate view. This setup allows users to access the contact form through a specific web address and ensures that the form is processed correctly.
  5. Admin Interface: Register the model with Django’s admin interface to manage and review contact messages. This step allows you to view submitted messages and perform administrative tasks directly from the Django admin panel.
  6. Design the HTML Template: Finally, create an HTML template for the contact form. This template will define the layout and styling of the form, including how the form fields are presented and how success or error messages are displayed.

This template includes a simple form structure, leveraging Django’s template language to handle CSRF protection and dynamic URL resolution. It ensures a secure and user-friendly experience for submitting contact information.

Conclusion

In this guide, we’ve explored the process of building a contact form with Django, from defining the model and form to configuring the view and setting up URLs. We’ve also discussed how to manage contact messages using Django’s admin interface and how to design a user-friendly HTML template.

By following these steps, you can create a fully functional contact form that integrates seamlessly into your Django application. Whether you’re building a personal website or a large-scale web application, Django provides the tools you need to manage user interactions effectively.

If you found this guide helpful, be sure to explore more of my content for additional tips and tutorials on Django and web development. You can follow my YouTube channel for video tutorials, visit my Instagram for updates and insights, and read my blog for more in-depth articles and guides.

Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *


Shopping Basket
Scroll to Top