Hello everyone. In this post, I am going to show you guys how you can save user entered form data to database and view those data in the admin dashboard in python. Before starting this tutorial, I assume that you all have python and Django framework installed on your machine. I will be using Pycharm for building the same application. You can use whatever IDEs you love like Visual Studio Code, Sublime Text, Pydev and so on. So lets start.
So first I will be opening the cmd and save my project directory into the desktop. You can go to your dektop by typing cd desktop. After then you can create your project name by typing django-admin startproject project1. Then go to that project directory by typing cd project1 and finally 'python manage.py startapp demo' to build your first app.

You can type python manage.py runserver to check whether you have successfully setup everything to build your project. If everything is ok then go to your browser and type http://127.0.0.1:8000/ into the address bar. You should see something like this one.

Your project structure should look something like this one.

You can use the pycharm terminal to run various django commands but I am using the Windows command prompt to do so. So first lets render a form template to our home page. Before rendering that we need to do few things. Inside our demo directory, we need to create another directory and name it as templates. Again inside the templates directory, we need to create another directory and name it as demo. Because this is the Django way of building any project and this convention is followed by every software developers out there. Finally inside our newly created demo folder we will add a new HTML file and name it as 'form.html'.
Now your project structure looks something like this:

Now lets add some HTML code to our form.html. I wouldn't be doing it from scratch because this will be too time consuming. Rather I would be copying it from official Bootstrap website. You can find Starter Template in this website. Copy this and paste it in your form.html. Inside the body tag, I would be copying this Form Overview HTML code and modify it a little bit. So this is what is inside our form.html. You can copy paste this directly.
<!doctype html>
<html lang="en">
<head>
(html comment removed: Required meta tags )
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
(html comment removed: Bootstrap CSS )
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<title>Django Tutorial</title>
</head>
<body>
<div class="container">
<h1>Basic Form</h1>
<hr>
<form>
<div class="mb-2">
Name:
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="mb-2">
Email address
<input type="email" class="form-control" id="email" name="email">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-2">
Phone:
<input type="text" class="form-control" id="phone" name="phone">
</div>
<div class="mb-2">
Your Concern:
<textarea class="form-control" id="concern" name="concern" rows="6"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
</body>
</html>
For now we just want user to enter four things in the form: their name, their email, their phone and their concern. Now lets render this form.html in our browser. Go to project1/project1/urls.py and we need to add path to point to our app which is in this case is demo. So first of lets import include and add one more URL patterns to this file. It should look something like this.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('accounts.urls'))
]
Second go to project1/settings.py. You can see the list of 'INSTALLED_APPS'. In the same list we need to add our app name, which in this case is demo.
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'demo',
]
Now lets create a view. We have already created form.html and we would render this out to our view. Inside 'project1/demo/views.py', lets add this to our code.
from django.shortcuts import render
def home(request):
return render(request, 'demo/form.html')
Now create a new file name 'urls.py' inside a 'demo' directory. And we want to specify the path to URLs i.e whenever user places link to homepage, we want them to show specified view (which is form template in this case).
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="contact"),
]
Now its time to see if our template has been rendered. Check the terminal if the server is still running. If not type 'python manage.py runserver'. If everything is correct, it won't throw any error. So here we have finally rendered our form template.

Now a few things remain. Our goal is to fill this form and save the form data to the database and see those data in the admin dashboard. So to do that, lets go to 'demo/models.py' and we need to create models with those form fields i.e. name, email, phone and your concern.
from django.db import models
class Queryform(models.Model):
name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
phone = models.CharField(max_length=200)
concern = models.TextField(max_length=600)
def __str__(self):
return self.name
Now lets tell Django to prepare database table for us. To do so, go to terminal and type python manage.py makemigrations and hit enter. You should see something like this:

You should see something like 0001_initial. py file inside migrationsdirectory.

So now lets actually create a database for us. To do that go to terminal and type 'python manage.py migrate' and you should see something like this.

Before creating a superuser to view dashboard, lets first register our Queryform model inside admin. To do so, go to demo/admin.py. First we need to import our models so type this from .models import Queryform in top and finally register our model. So this is what should be inside 'admin.py'
from django.contrib import admin
from .models import Queryform
admin.site.register(Queryform)
Now go to terminal and type 'python manage.py createsuperuser'. This is what you should see. You can't see anything in the screen while typing password but its actually being typed in the backend so don't panic.

Now time to open our admin dashboard. Type python manage.py runserver. Go to browser and type http://127.0.0.1:8000/admin in address bar. This is what appears there.

Enter your username and password and you should see something like this in your dashboard.

See our model have been already there and those specified fields are already there.

Now we are at the end to what we want to achieve i.e enter data in the form from the front-end, save it to database and show it in dashboard under "Queryforms." Lets go to our form.html and we need to add few things there. Add this line of code to your
tag.<form method="post" action="{% url 'contact' %}">
{% csrf token %}
We need to mention csrf_token to prevent agains cross site scripting attack. Now go to our views.py and we need to import our models and then save those form data to the Queryform models. Also we want to show success messages to the user to tell them that their query has been received. So for this we need to import messages provided by django libaries. This is what our views.py looks now.
from django.shortcuts import render
from .models import *
from django.contrib import messages
def home(request):
if request.method == "POST":
name = request.POST.get("name")
email = request.POST.get("email")
phone = request.POST.get("phone")
concern = request.POST.get("concern")
query_info = Queryform(name=name, email=email, phone=phone, concern=concern)
query_info.save()
messages.success(request, "Your query has been received successfully.")
return render(request, 'demo/form.html')
Also we need to modify our 'form.html' a little bit because we want users to show their message status in the same page. This is our modified 'form.html'.
<!doctype html>
<html lang="en">
<head>
(html comment removed: Required meta tags )
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
(html comment removed: Bootstrap CSS )
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<title>Django Tutorial</title>
</head>
<body>
<div class="container">
<h1>Basic Form</h1>
<hr>
<form method="post" action="{% url 'contact' %}">
{% csrf_toke %}
{% if messages %}
{% for message in messages %}
<button class="btn btn-success">{{ message }}</button>
<br><br>
{% endfor %}
{% endif %}
<div class="mb-2">
Name:
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="mb-2">
Email address
<input type="email" class="form-control" id="email" name="email">
<div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
</div>
<div class="mb-2">
Phone:
<input type="text" class="form-control" id="phone" name="phone">
</div>
<div class="mb-2">
Your Concern:
<textarea class="form-control" id="concern" name="concern" rows="6"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
</body>
</html>
Now time to test our code. Check if your server is running. If not type python manage.py runserver.

I want to submit these data and when I clicked submit the follwing picture appears telling that our query has been received.

Now go to your admin dashboard and click "Queryforms". You can see one query has been received.

When you click that, you can see all the data submitted by your customers or users, which is as below.

Last but not least there is one problem that has persisted. A user can submit empty form and pollute our dashboard. As for example, when I click submit without entering any info, you can see in the dashboard like this.

We need to add some kind of validations for this otherwise our application may crash when someone wrote scripts to submit empty data to our dashboard. We can add javascript validation in the client side to protect anyone from submitting the empty data or when someone fails to enter one or more than one fields. For this we can add javascript to our form.html. In <form> tag lets add few attribute we need to give it name ="query_form" and onsubmit="return validateForm()". Under our closing <body> tag lets add this javascript.
<script>
function validateForm() {
var x = document.forms["query_form"]["name"].value;
var y = document.forms["query_form"]["email"].value;
var z = document.forms["query_form"]["phone"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
if (y == "") {
alert("Email must be filled out.");
return false;
}
if (z == "") {
alert("Phone must be filled out");
return false;
}
}
</script>
Now lets test our code. See if your server is stil running. Mine is running.
When I try to submit an empty form this is the error I get.

When I try to left phone field empty filling other fields, this is the error I get

So we have successfully completed our simple project of submitting form data to the database and showing those in the database along with validation added to the form. Below is the source code to the same project.
http://www.mediafire.com/file/mph72qxrt5yu7rq/project1.zip/file
Getting Started
Username: testuser
Password: testuser123