Dynamic Creation of Thematic Indexes – Static Website

I will use Python Django to create a website so the users can enter a few stocks they come up with fundamental research, hit a button, and a full-blown csv sheet will be automatically generated with all similar companies of their interest.

After setting the python3 environment(refer to the previous blog), and install Django(supplementing the details later).

Now to start a project/website, type

django-admin startproject sitename

Then create an app/subwebsite in the main website

python manage.py startapp theme

There are several py files attached when the website and theme subwebsite are created. Right on the root directory(herein refers to mainwebsite, there are theme folder, website folder, manage.py and db.sqlite3 gadgets, underneath theme, there are __init__.py, admin.py, apps.py, models.py, tests.py, views.py, and migrations, __pycache__ folder. Underneath another website folder under website, there are __init__.py, settings.py, urls.py, and wsgi.py files.

These file are cross talking to each other to make my task work. 1. go the settings.py file under website folder, to add the theme in the INSTALLED_APP list.

# Application definition

INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘theme’,
]

2. go to the “theme” folder, and edit the views.py as

from django.shortcuts import render
from django.http import HttpResponse

def myView(request):
return HttpResponse(‘HELLO …………….. test!’)

3. to make the Django recognize the new view should be effect, go to the urls.py under the website folder, open it with the modification as

“”website URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path(”, views.home, name=’home’)
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path(”, Home.as_view(), name=’home’)
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path(‘blog/’, include(‘blog.urls’))
“””
from django.contrib import admin
from django.urls import path
from theme.views import myView

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘theme/’, myView),
]

Now run python manage.py runserver, we shall get this view:

Next, I want to make the interface dynamic that the users can input info. Django’s “templates” comes into play. So first create templates folder under webiste, by type mkdir templates, then create toenter.html in templates by typing copy NUL toenter.html, edite toenter_html by adding the first line: <h1>this is the entering page.<h1>, toggle back to the views.py under theme folder, we need to edit the views setting, instead of returning a static http responding text, we render it per request:

from django.shortcuts import render
from django.http import HttpResponse

def myView(request):
return render(request, ‘toenter.html’)

After views.py is set, we need to instruct the setting.py under website to follow through by fill in the DIR path:

TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],
‘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’,
],
},
},
]

Next, we need to interact with database to produce output, the core value of this website, to do this, we need to use models.py under the theme folder. If we edit the models.py as

from django.db import models

class TodoItem(models.Model):
content = models.TextField()

then go the windows terminal/cmd to type python manage.py makemigrations, to change the configuration of default database

Then type python manage.py migrate, we get “Applying theme.0001_initial… OK”. We can now play around in cmd window to learn this database objects:

from theme.models import TodoItem
all_todo_items[0].content
a = TodoItem(content=’permenant A’)
a.save()
all_todo_items = TodoItem.objects.all()
all_todo_items[0]
all_todo_items[0].content
all_todo_items[1].delete()
all_todo_items[0].id
TodoItem.objects.get(id=1)

Then to put this simple db in use, we modify the views.py in theme again:

from django.shortcuts import render
from django.http import HttpResponse
from .models import TodoItem

def myView(request):

all_todo_items = TodoItem.objects.all()
return render(request, ‘toenter.html’,
{‘all_items’: all_todo_items})

And the html template file needs to edit accordingly.

Finally, compiling all relative files here:

  1. views.py
  2. toenter.html
  3. models.py
  4. urls.py
  5. setting.py

1.views.py

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .models import TodoItem

def myView(request):

all_todo_items = TodoItem.objects.all()
return render(request, ‘toenter.html’,
{‘all_items’: all_todo_items})

def addTodo(request):
new_item = TodoItem(content = request.POST[‘content’])
new_item.save()
return HttpResponseRedirect(‘/theme/’)

def deleteTodo(request, todo_id):
item_to_delete = TodoItem.objects.get(id=todo_id)
item_to_delete.delete()
return HttpResponseRedirect(‘/theme/’)

3.models.py

from django.db import models

class TodoItem(models.Model):
content = models.TextField()

2.toenter.html

this is the entering page.

<!–

  • Please enter stock symbols here
  • Please enter stock SEDOL here

–>

    {% for todo_item in all_items %}

  • {{ todo_item.content }}
    {% csrf_token %}

  • {% endfor %}

{% csrf_token %}

4. urls.py

“””website URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path(”, views.home, name=’home’)
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path(”, Home.as_view(), name=’home’)
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path(‘blog/’, include(‘blog.urls’))
“””
from django.contrib import admin
from django.urls import path
from theme.views import myView, addTodo, deleteTodo

urlpatterns = [
path(‘admin/’, admin.site.urls),
path(‘theme/’, myView),
path(‘addTodo/’, addTodo),
path(‘deleteTodo//’, deleteTodo),
]

5. settings.py

“””
Django settings for website project.

Generated by ‘django-admin startproject’ using Django 2.1.5.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
“””

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, …)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings – unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ‘(9n2946wc#e0xl11gp0f8^+&v1wql8b(1y7i**4uy$%nhh*=x)’

# SECURITY WARNING: don’t run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘theme’,
]

MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’,
]

ROOT_URLCONF = ‘website.urls’

TEMPLATES = [
{
‘BACKEND’: ‘django.template.backends.django.DjangoTemplates’,
‘DIRS’: [os.path.join(BASE_DIR, ‘templates’)],
‘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’,
],
},
},
]

WSGI_APPLICATION = ‘website.wsgi.application’

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

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

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
‘NAME’: ‘django.contrib.auth.password_validation.UserAttributeSimilarityValidator’,
},
{
‘NAME’: ‘django.contrib.auth.password_validation.MinimumLengthValidator’,
},
{
‘NAME’: ‘django.contrib.auth.password_validation.CommonPasswordValidator’,
},
{
‘NAME’: ‘django.contrib.auth.password_validation.NumericPasswordValidator’,
},
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = ‘en-us’

TIME_ZONE = ‘UTC’

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = ‘/static/’

The final output:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.