Django – Making a contact form and storing its data without model, query and html

In Django, you can create a contact form very easily but it takes managing a lot of things like making forms, views, models, and then register the model in Admin, etc. In this article, we will see how to use a predefined package for our contact form which will save the data in a predefined model.

We will make a contact form which will store data in model without writing any code in models.py or views.py or writing any html. So, let's get started.

Example

First, create a Django project and an App.

Install the django-contactforms package −

pip install django-contactforms

Then, in settings.py, add the following line −

INSTALLED_APPS+=["contactforms"]

Add this module and your app name in INSTALLED_APPS.

In urls.py of project −

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

urlpatterns = [
   path('admin/', admin.site.urls),
   path('', include('contactforms.urls')),
   path("aftercontact", include('MyForm.urls'))
]

Create two URL endpoints, one for contact form and the other for redirecting after submitting.

In urls.py of app −

from django.urls import path,include
from . import views
urlpatterns = [
   path('',views.home,name="home"),
]

Here, we rendered the html which we will show after filling the contact form.

In views.py

from django.shortcuts import render
# Create your views here.
def home(request):
   return render(request,"home.html")

Here we rendered our html.

Now, create a folder in the App directory and name it "templates". Add a folder inside it and call it "contact" and add a html file inside it and name it contact.html. Add the following lines in contact.html.


   
      
     
     

Send a Message

      {% csrf_token %}      
         {% if messages %}          {% for message in messages %}                       {{ message }}                    {% endfor %}             {% endif %}      
     
         {{ forms.name }}      
     
         {{ forms.email }}      
     
         {{ forms.subject }}      
     
         {{ forms.message }}      
         
   
   

This is the form that will be shown on "/" endpoint. We simply loaded the form from our package.

Now come back to templates folder and add home.html (not inside contact folder) and add the following lines −


   tut
   
      

Successfull

   

Output

This is the html which is rendered after submitting the contact form.

Updated on: 2021-08-26T12:15:56+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements