Install Django Using IDE Pycham

By ukmodak | August 12th 2022 07:07:45 PM | viewed 29 times
Step 1:

Install python 3.6.5

Install pycham

Open pycham and create a project with name:djangotest

Step 2:

find out the djangotest project size before installing django (42.6 MB)

open terminal from pycham

run the folllowing command to install django tools

djangotest>pip install django
Step 3:

to create django project run the following command

 
  djangotest>django-admin  startproject uktest .            // create project
  djangotest>django-admin  startapp hong                    // to create different app under project
  djangotest>python manage.py runserver       // run project
Step 4:

browse:http://127.0.0.1:8000/

After creating project some file introduction

  • djangotest
    • uktest is the django main project directory
      • __init__.py
      • asgi.py
      • settings.py this file setup root urls,database ,app
      • urls.py this file setup admin url,include all apps url
      • wsgi.py
    • hong -- is the app(application directory whis is setup in uktest.settings.py file)
      • migrations
      • __init__.py
      • admin.py
      • apps.py -- is the app config file
      • models.py -- is contain all model class
      • tests.py
      • views.py --is contail all method or class
      • urls.py -- is setup all method url
    • venv -- contain all downloaded library
    • db.sqlite3 -- default sqlite database
    • manage.py -- by this execute all command
  • manage.py is a command-line utility which allows us to interact with Django project in various ways.
  • djangotest sub-directory is actually a Python package for our project. We can import this package(a group of modules) and its contents just like we import any general Python package/module and its contents.
Step 5:

To create auth table using mysql

pip install mysqlclient

settings.py =>

DATABASES = {
	'default': {
		'ENGINE': 'django.db.backends.mysql',
		'NAME': 'db_uktest',
		'USER': 'root',
		'PASSWORD':"",
		'HOST': "",
		'PORT': "",
		'OPTIONS': {
		    'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
		}
	}
}

Open the mysql databse and found to table create

Run the following command to create acl table on the database

  djangotest>python manage.py makemigrations
  djangotest>python manage.py migrate

Open the mysql databse and found 10 acl table created (auth_group,auth_group_permissions,auth_permission,auth_user,auth_user_groups, auth_user_user_permissions,django_admin_log,django_content_type,django_migrations, django_session )

  djangotest>python manage.py createsuperuser

http://127.0.0.1:8000/admin/ and enter: user:uzzal,email:uzzalmodak@yahoo.com,pass:password

Or create auth table using default sqllite database

settings.py =>

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

browse the link and upload db.sqlite file from your porject to see default no. of table and their column https://sqliteonline.com/

Run the following command

  djangotest>python manage.py makemigrations
  djangotest>python manage.py migrate

again browse the link and upload db.sqlite file and found some table has been createdhttps://sqliteonline.com/

  djangotest>python manage.py createsuperuser

http://127.0.0.1:8000/admin/ and enter: user:uzzal,email:uzzalmodak@yahoo.com,pass:password

django documentation linkhttps://docs.djangoproject.com/en/4.0/

Step 6:

After creating the application hong you must setup under main project directory settings.py as follows.

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

Django follow MVT architecture(model->view->template insted model->view->conteoller)

Create a file models.py in hong app which treat like model and add following code

from django.db import models

class Student(models.Model):
	roll_no = models.TextField()
	name = models.TextField(max_length = 40)
	stud_class = models.TextField()
	department = models.TextField()

Now, execute these commands.

djangotest>python manage.py makemigrations
djangotest>python manage.py migrate

Now open the main database that you have created for this Django project. Then, check the table hong_student(namming convention appName_modelName)

Step 7:

Django Views Component

In our hong app directory create a new python file named views.py. and add the following code


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

def student_show(request):
    x = []
    for i in range(10):
        x.append(i)
    return HttpResponse("

Hi UK Modak

The Digits are {0}".format(x))

Here we have imported HttpResponse from the library django.http because we need to respond in the HTTP format. Also, we are passing the parameter request to the function.

Every view function will have their first parameter as request.

After that, we wrote a simple python program of storing digits 0-9 in a list and we passed on that list as a string to the HttpResponse. It will then covert the same as HTTP and that will be returned to our browser as HTML which then renders it that way.

This Views file is special as you can see, we are passing HTML as a string and that presents on the browser.

In our hong app directory create a new python file named urls.py. and add the following code

from django.urls import path
from . import views
urlpatterns = [
path('student/show', views.student_show, name = 'student_show'),
]

Here, we are creating a urls file for our application rather than the whole project. This urls file will contain all the URLs inside it related to our app. Thus, we get a cleaner main urls_config file.

Now, we will be connecting our project with the application.

Open the urls.py file of the project that is in the root folder.

Now add this hong.urls.py in the main project(uktest) urls.py file as follows


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

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


To run this view simply type in the url bar, http://localhost:8000/student/show

Step 8:(Create another oracle connection and render output)
djangotest>pip install cx_Oracle
djangotest>pip install xlwt
djangotest>pip install json

create a text file db_connection.txt in the the location:D:\\db_connect_info\\uk\\ and the following code

ukuser/ukpass@UZZAL-PC/db11g

add the following code in hong.views.py file

from django.views import View
import cx_Oracle
import json
import datetime
import xlwt
import ast


def get_connection_info_uk():
    with open("D:\\db_connect_info\\uk\\db_connection.txt") as f:
        conn_info = f.readlines()
    conn_info = [x.strip() for x in conn_info]
    return conn_info

def query_db(query, args=(), one=False):
    try:
        list_conn_info = get_connection_info_uk()
        db_connection_info = str(list_conn_info[0])
        con = cx_Oracle.connect(db_connection_info)
        cur_oracle = con.cursor()
        cur_oracle.execute(query, args)
        r = [dict((cur_oracle.description[i][0], value) \
                  for i, value in enumerate(row)) for row in cur_oracle.fetchall()]
        cur_oracle.connection.close()
        return (r[0] if r else None) if one else r
    except:
        pass
		
def myconverter(o):
    if isinstance(o, datetime.datetime):
        return o.__str__()

def item_detail(request):
    if request.method == 'GET':
        print(request.GET)
        l_data = request.GET
        l_dic = l_data.dict()
        oracle_sql = '''SELECT *
                          FROM inv_sales_dtl
                         ORDER BY id asc'''
        my_query = query_db(oracle_sql)
        l_json_output = json.dumps(my_query, default=myconverter)
        return HttpResponse(l_json_output)

Add this following code in hong.urls.py file

path('student/item_detail', views.item_detail, name='item_detail'),

To run this view simply type in the url bar, http://localhost:8000/student/item_detail

bONEandALL
Visitor

Total : 9222

Today :7

Today Visit Country :

  • United States