The real estate application is already designed and is running on the local server. There are many things we can do to make this application a sophisticated one. However, only two are within the scope of this project. We want to add a contact form so that anyone who needs more information about properties listed in the app can easily contact us.
At the same time, we can’t just let “strangers” contact us. Interested individuals must be duly registered on our platform. Thus, in upcoming project tutorial, we will add a user authentication feature to this application.
Remember that this is a continuation of the real estate application project. The full code is on GitHub.
Steps in Creating a Contact Form
We have already created a contact form page when designing a portfolio website. I could have told you guys to go through that tutorial and not spend another time repeating what I have already done previously. However, since this contact page will have a feature not added in that tutorial, I have to design it again.
This will also add to your knowledge as you see various ways to do the same thing using the Django web framework. Here are the steps to get this contact form designed on our application:
- Create a model for the contact form.
- Create a view to handle GET and POST request
- Restrict access to the view
- Add a template to render the view
- Map the view to a URL route
The Model
The model will be used to store the messages in the database. It’s going to contain the name, email, messages and the date the message was received in the database.
from datetime import datetime class Contact(models.Model): name = models.CharField(max_length=50) email = models.EmailField() submitted_on = models.DateTimeField(default=datetime.now) message = models.TextField() def __str__(self): return self.name
Next is to apply migrations. Then we proceed to create a contact form in the forms.py
file.
The Form
We will subclass the forms.ModelForm
class to direct all messages to the database.
from django import forms from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name', 'email', 'message']
We modify the behavior of the Contact model using the Meta class to display selected fields.
The Views
We will use function-based views instead of the class-based views we used in the first contact form we made.
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import ContactForm @login_required(login_url=‘login’) def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Save the data to the database form.save() return redirect('home') else: form = ContactForm() return render(request, 'contact.html', {'form': form})
In this view, we are using Django’s @login_required
decorator to restrict access to the contact
view. If a user tries to access this view without being authenticated, they will be redirected to the login page.
We create an instance of the ContactForm
class. Once the user enters the required fields defined in the forms.py
file and submits the form, it will check whether the form is valid before saving it to the database.
Once the form has been successfully validated and saved, it will redirect the user to the home page. If, though, the request method is GET, it will create an instance of the form and pass it to the render()
function to be displayed on a template.
The Template
Next, let’s create a template for our contact form. In the templates/contact.html
file, add the following code:
{% extends 'base.html' %} {% load tailwind_filters %} {% block content %} <div class="col-md-8 card mb-4 mt-3"> <h1 align="center">Contact Form</h1> <hr> <p>Please fill out this form to contact us for more information.</p> <hr> <br> <form method="post"> {% csrf_token %} {{ form | crispy }} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form> </div> {% endblock %}
In this template, we are using Django’s built-in forms to create the contact form fields, and crispy tailwind to give it a nice appearance.
The URL will be:
from .views import contact path('contact', contact, name='contact'),
The Admin
To see the Contact model in the admin panel, we have to register it in the admin.py
file.
from .models import Contact admin.site.register(Contact)
Login to your admin panel to see the Contact
model.
A little adjustment
I made some modifications to the real estate application. Check my GitHub page to see the full code. Here are some of the adjustments I made:
- Changing the name of the home page template;
- Allowing only the admin to perform CRUD operations by removing the update, edit and delete links;
- Restricting access also to the retrieve view;
- The link to the contact page now appears on the home page
Visitors to the website can only see several properties listed but won’t be allowed to access the READ MORE link as well as the contact page without registering on the platform.
- Giving users the option to log out after logging in. The link now appears on the
retrieve.html
template.
- Creating the user authentication feature. Check out this article where I showed how I added the register, login and logout functionality in this application.
Conclusion
We come to the end of this tutorial. The application now has a contact page where registered users can reach out to us to know more about properties available for sale.
This is just a simple demonstration of how Django can be used to build applications. Yes, complex applications which are far beyond the scope of this project tutorial.
By taking them one step at a time, you will get to your destination.