Online Document Scanning with Django and Dynamic Web TWAIN
Tags: django, web, document, management
Published: 2021-09-22 07:58:19

Django is a popular framework of Python for web development. In this tutorial, we will create a web application with [Django](https://docs.djangoproject.com/en/3.2/) and [Dynamic Web TWAIN](https://www.dynamsoft.com/web-twain/overview/).

## About Dynamic Web TWAIN
- [https://www.dynamsoft.com/web-twain/downloads](https://www.dynamsoft.com/web-twain/downloads)
- [https://www.dynamsoft.com/customer/license/trialLicense/?product=dwt](https://www.dynamsoft.com/customer/license/trialLicense/?product=dwt)

## Python Development Environment

- Python 3.7.9

    ```bash
    python --version
    ```

- Django 3.2.7
    
    ```bash
    python -m pip install Django
    python -m django --version
    ```


## Overall steps

The steps that integrate Django with Dynamic Web TWAIN are:

1. Create a Django project.
2. Create an app inside the project.
3. Create an HTML template that loads the Dynamic Web Twain library. The library path is dynamically generated by template syntax.
4. Configure the path of static resource files.

## Create your project with Django

Open your terminal to create a project with Django using the following command (applicable for Windows, Linux, macOS):

```bash
python -m django startproject djangodwt
```

Once completed, you will see the newly created project folder under your **working directory**.

![Django working directory](https://www.dynamsoft.com/codepool/img/2020/09/django-created-app-1.png)

Then, change your directory to `djangodwt` and run the app using the following command:

```bash
cd djangodwt
python manage.py runserver
```

After the server has been successfully started, you can visit `http://127.0.0.1:8000` in a web browser.

![new Django project](https://www.dynamsoft.com/codepool/img/2020/09/django-server-up-1-1000x922.png)

Now, a simple Django project has been successfully created.

## Integrating with Dynamic Web TWAIN

### Create the App

To build your web scanner app, you should firstly create an app.

```bash
python manage.py startapp dwt
```

> In Django, project and app are different terminologies. An app is a Web application that does something. A project is a collection of apps that serve a particular website. For more details, refer to [Writing your first Django app](https://docs.djangoproject.com/en/3.1/intro/tutorial01/).

Now, the project structure is as follows.

```plain
djangodwt
  - djangodwt
    - __pycache__
    - asgi.py
    - settings.py
    - urls.py
    - wsgi.py
    - __init__.py
  - dwt
    - migrations
      - __init__.py
    - admin.py
    - apps.py
    - models.py
    - tests.py
    - views.py
    - __init__.py
  - db.sqlite3
  - manage.py
```

### Create the view for Dynamic Web TWAIN

We will use a template to create our view. Conventionally, your template files should be placed under `{project_folder/templates/{app_named_folder}/}`. Let's create one named `index.html`.

```html
<!DOCTYPE html>

<head>
  <title>Dynamic Web Twain</title>
  <meta charset="utf-8">
  {% raw %} {% load static %} {% endraw %}
  <!-- Import Dynamic Web Twain library. Template will compile the actual path for us. -->
  {% raw %} <script type="text/javascript" src="{% static 'dwt/Resources/dynamsoft.webtwain.initiate.js' %}"></script> {% endraw %}
  {% raw %} <script type="text/javascript" src="{% static 'dwt/Resources/dynamsoft.webtwain.config.js' %}"></script>  {% endraw %}
</head>

<body>
  <div id="app">
    <div id="dwtcontrolContainer"></div>
    <button onclick="scan()">Scan</button>
  </div>
  <script type="text/javascript">
    Dynamsoft.DWT.RegisterEvent('OnWebTwainReady', Dynamsoft_OnReady);
    Dynamsoft.DWT.ResourcesPath = 'static/dwt/Resources';
    Dynamsoft.DWT.ProductKey = 'LICENSE-KEY';
    var dwtObjct;

    function Dynamsoft_OnReady() {
      dwtObjct = Dynamsoft.DWT.GetWebTwain('dwtcontrolContainer');
    }
    function scan() {
      if (dwtObjct) {
        dwtObjct.OpenSource();
        dwtObjct.IfDisableSourceAfterAcquire = true;
        dwtObjct.AcquireImage(() => {dwtObjct.CloseSource();}, () => {dwtObjct.CloseSource();});
      }
    }
  </script>
</body>
```

Notice that you need a [valid license](https://www.dynamsoft.com/customer/license/trialLicense?product=dwt) key and update `Dynamsoft.DWT.ProductKey = 'LICENSE-KEY'` to make scanner API work. The `ResourcesPath` is the path to the `dynamsoft.webtwain.initiate.js` and `dynamsoft.webtwain.config.js` files. We will discuss this later.

Then we open the file `dwt/views.py` and put the following Python code in it:

```python
from django.http import HttpResponse, request
from django import template
from django.shortcuts import render
import os

def index(request):
  return render(request, 'dwt/index.html')
```

In the app folder (`{project_folder}/dwt` in this case), we create another file called `urls.py` and include the following code.

```py
from django.urls import path
from . import views

urlpatterns = [
  path('', views.index, name='index')
]
```

Next, we go to the project's `urls.py` file, which is located in `{project_folder}/{project_name}`. We include the newly defined rules.

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

urlpatterns = [
  path('admin/', admin.site.urls),
  path('', include('dwt.urls'))
]
```

Finally, configure the templates directory in `settings.py`. We specify the template DIR as follows.

```py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],  # this field
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
```


### Import Dynamic Web TWAIN

Now, it's time to import Dynamic Web TWAIN resource files to this project.

Steps:
1. Create a `static` folder under the project root.
2. Create a `dwt` folder under `static` folder.
3. Copy and paste `Dynamic Web TWAIN SDK version/Resources` folder to `static/dwt/`.

Afterwards, we append the following code to `settings.py` to make `static/dwt/Resources` accessible.

```py
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]
```

The web document scanning application developed with Dynamic Web TWAIN and Django should now work successfully.

![Web document scan by Python Django](https://www.dynamsoft.com/codepool/img/2020/09/django-working-1-1000x578.png)

![Web document management by Python Django](https://www.dynamsoft.com/codepool/img/2020/09/django-scan-upload-document.jpg)

### How to Upload Documents to Django Database
Django provides a built-in `django.db.models.Model` class to store data in the database. The `Model` class is the base class for all models in Django.

Let's define a model class to store scanned documents in `dwt/models.py`:

```python
from django.db import models

class Image(models.Model):
    name = models.CharField(max_length=30)
    data = models.ImageField(upload_to='images/')

    def __str__(self):
        return self.name
```

To use the model, we need to add the name of the module that contains `models.py` in `djangodwt/settings.py`:

```python
INSTALLED_APPS = [
    #...
    'dwt',
]
```

Now, we can use the following code to store scanned documents in `dwt/views.py`:

```python
from .models import Image

def upload(request):
    if request.method == 'POST':
        image = Image()
        image.name = request.FILES['RemoteFile'].name
        image.data = request.FILES['RemoteFile']
        image.save()
        return HttpResponse("Successful")

    return HttpResponse("Failed")
```

To verify whether the database operation is successful, you can open the `db.sqlite3` file in a DB browser and check its status change after uploading a document image.

![Django database for storing scanned documents](https://www.dynamsoft.com/codepool/img/2020/09/django-database-image-store.jpg)

## Source Code

[https://github.com/dynamsoft-dwt/Scan-Documents-with-Python](https://github.com/dynamsoft-dwt/Scan-Documents-with-Python)