Django provides a powerful form-handling system that simplifies the creation and processing of form data. Thanks to the Forms
class of Django, we can quickly create custom contact forms without writing extensive boilerplate code. Additionally, Django’s forms are equipped with built-in protection against common security threats, such as Cross-Site Request Forgery (CSRF) attacks, ensuring the integrity and security of form submissions. The Django admin interface further enhances form management by providing administrators with a user-friendly interface for viewing, editing, and deleting form submissions.
Django is based on MVC architecture, so building a contact form involves defining a model to structure the data and configuring views to handle form submissions, ensuring efficient organization and maintainability.
Below is a simple Django application that has not yet implemented the contact form functionality.
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
Note: Click on the app URL to open the application in a new browser window once this message appears in the terminal: "Starting development server at http://0.0.0.0:8000/".
Now we’ll start by defining the model in the models.py
file of our application. The modified code of this file is shown below:
from django.db import modelsclass Contact(models.Model):name = models.CharField(max_length=100)email = models.EmailField()message = models.TextField()date_added = models.DateTimeField(auto_now_add=True)def __str__(self):return self.name
Our model has four fields: name, email, message, and the date on which the form is submitted. Once the model has been created, we define the structure of the form by creating a forms.py
in the myapp
directory and then write the code for that file. The code will look as follows:
from django import formsfrom .models import Contactclass ContactForm(forms.ModelForm):class Meta:model = Contactfields = ['name', 'email', 'message']
This form will be used to populate the Contact
model that we defined earlier. It has three fields: name, email, and message. Now, we’ll implement the controller part. We’ll start off by creating a views.py
file in our myapp
directory. The code of that file will look as follows:
from django.shortcuts import render, redirectfrom .forms import ContactFormdef contact(request):if request.method == 'POST':form = ContactForm(request.POST)if form.is_valid():form.save()return redirect('success')else:form = ContactForm()return render(request, 'myapp/contact.html', {'form': form})def success(request):return render(request, 'myapp/success.html')
This function takes the user to the form and based on the submission, takes them to the success page.
The next step in controller implementation is to define the path that’ll make this views.py
execute. To do this, we’ll need to modify the urls.py
file in the myproject
directory. The modified code will look as follows:
from django.contrib import adminfrom django.urls import path, includeurlpatterns = [path('admin/', admin.site.urls),path('', include('myapp.urls')),]
from django.urls import pathfrom . import viewsurlpatterns = [path('', views.contact, name='contact'),path('success/', views.success, name='success'),]
The last step is the views implementation. To do this, create a templates
folder in myapp
directory. Now, within the newly created folder, create another folder called myapp
. Within that folder, create two HTML pages, contact.html
and success.html
. The contents of the contact.html
file is as follows:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Contact Form</title></head><body><h2>Contact Us</h2><form method="post">{% csrf_token %}{{ form.as_p }}<button type="submit">Submit</button></form></body></html>
Here’s the success.html
file:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Success</title></head><body><h2>Thank you for contacting us!</h2></body></html>
Now, all we need to do is migrate these changes by running the following commands:
python manage.py makemigrationspython manage.py migrate
We can then run our application with this command:
python manage.py runserver
Note: You don't need to execute the above mentioned commands. The application is already executed for you in the below widget.
Here is a sample Django application with contact form implementation. The commands for migration and application execution will run automatically when you click the "Run" button in the widget below. The application will display a form with a "Name", "Email", and a "Message" field with a "Submit" button. Fill the fields with appropriate values and click the "Submit" button to send the response. This will display a page containing the "Thank you for contacting us!" text.
from django.db import models class Contact(models.Model): name = models.CharField(max_length=100) email = models.EmailField() message = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name
Note: Click on the app URL to open the application in a new browser window once this message appears in the terminal: "Starting development server at http://0.0.0.0:8000/".
We have built a contact form with Django, showcasing its simple and efficient form-handling system. We integrated a secure contact form into a Django application by defining models, creating forms, setting up views, and configuring URLs. This approach reduces boilerplate code and leverages Django’s built-in CSRF protection. With this foundation, you can customize your forms for more complex requirements, enhancing your web applications with robust form processing capabilities.
Free Resources