How to Entry Data using Form to PostgreSQL Database in Django

Posted on

The article is to show how to entry data using a form. Those data will be available for further save operation to the PostgreSQL database. The form is available in a Django application. That form will receive a data by an entry process. In order to simulate the data entry process, there is a need to prepare several files so that the entry data process is possible. But first of all, the following is a tree structure directory of that project :

user@hostname:~/python/django/project$ tree -L 3
.
├── app
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   ├── models.py
│   ├── __pycache__
│   │   ├── admin.cpython-36.pyc
│   │   ├── forms.cpython-36.pyc
│   │   ├── __init__.cpython-36.pyc
│   │   ├── models.cpython-36.pyc
│   │   ├── urls.cpython-36.pyc
│   │   └── views.cpython-36.pyc
│   ├── templates
│   │   └── app
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── project
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── __init__.cpython-37.pyc
│   │   ├── settings.cpython-36.pyc
│   │   ├── settings.cpython-37.pyc
│   │   ├── urls.cpython-36.pyc
│   │   └── wsgi.cpython-36.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── static
    ├── css
    ├── img
    └── js

23 directories, 65 files
user@hostname:~/python/django/project$ 

The templates directory has the following directory structure for more detail in the tree or recursive view :

│   ├── templates
│   │   └── app
│   │       ├── add.html
│   │       ├── base.html
│   │       └── index.html

There are a few things which is important for the application to work perfectly. Below is the description of those things :

1. Define and register the application as a module for the project to recognize it. Edit settings.py and add the following line :

# Application definition

INSTALLED_APPS = [
    'app',
    'django.contrib.admin',
...

Just insert the application name in the INSTALLED_APPS part as in the above lines of configuration.

2. Next step, don’t forget the configuration for the database connectivity. It is also in the same file, just edit settings.py as follows :

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

# DATABASES = {
#    'default': {
#        'ENGINE': 'django.db.backends.sqlite3',
#        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#    }
# }

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'app',
        'USER': 'postgres',
        'PASSWORD':'',
        'HOST': 'localhost',
        'PORT':'5432',
    }
}

The above lines configuration has the commented section. That commented section is the original database connection configuration. But in this article, the database connection is going through PostgreSQL Database Server. So, the modification of database connection configuration is a necessary as it exist in the above lines of configuration for an example.

3. Create the model, form and also view associated with the entry data process. The following are the content of each file :

The content of models.py for defining a model :

from django.db import models

# Create your models here.
class MyModel(models.Model):
    name = models.CharField(max_length=100)

Next one, it is the content of forms.py for defining a form is in the following lines of script :

from django import forms
from app.models import MyModel

class MyForm(forms.ModelForm):
    name = forms.CharField(error_messages={'required':'Please enter your name'})

    class Meta:
        model = MyModel
        fields = ('name',)

The last one is the views.py file. It is important for defining a function or method in the view file for the form data entry processing :

def add(request):
    if request.method == "POST" or None:
        form = MyForm(request.POST or None)
        if  form.is_valid():
            form.save()
            return render(request,'app/list.html',{'form':form})
        else:
            form = MyForm()
            return render(request, 'app/add.html',{'form':form})
    else:
        form = MyForm()
        return render(request, 'app/add.html')

4. Don’t forget to execute for the migration process to create the database and the associated table structure. Just execute the following command :

python manage.py makemigrations

If the above command execution is a success, don’t forget to follow the command execution with the following command :

python manage.py migrate

5. After that, another important for the data entry processing is the template file. It exist in in an HTML form inside the templates directory. The name of the file in this article is ‘add.html’. The content exists below  :

{% extends 'asset/base.html' %}
{% block content %}
<form method="POST" action="{% url 'asset-add' %}">
{% csrf_token %}
<div class="form-group">
<label for="exampleInputName">Name</label>
<input type="text" class="form-control" name="name" aria-describedby="name" placeholder="Name">
</div>
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% endif %}

<button type="submit" class="btn btn-primary">Submit</button>
</form>
{% endblock %}

6. Test it by trying to entry a data. The following is the image of the form :

  1. Just insert any character in the text field, and if it is a success, the data will be available in the database. The following is the record exist because of the entry process in PostgreSQL Database Server :
user@hostname:~/python/django/project$ psql -Upostgres -h localhost app
psql (10.10 (Ubuntu 10.10-0ubuntu0.18.04.1), server 11.4)
WARNING: psql major version 10, server major version 11.
         Some psql features might not work.
Type "help" for help.

app=# \dt
                   List of relations
 Schema |            Name            | Type  |  Owner   
--------+----------------------------+-------+----------
 public | app_app                    | table | postgres
 public | auth_group                 | table | postgres
 public | auth_group_permissions     | table | postgres
 public | auth_permission            | table | postgres
 public | auth_user                  | table | postgres
 public | auth_user_groups           | table | postgres
 public | auth_user_user_permissions | table | postgres
 public | django_admin_log           | table | postgres
 public | django_content_type        | table | postgres
 public | django_migrations          | table | postgres
 public | django_session             | table | postgres

app=# select * from app_app;
 id |  name   
----+---------
  1 | Testing
(1 row)

app=# 

Leave a Reply