Build a Django Enabled web app using Database

Introduction

In this tutorial , I want to share the knowledge about connecting a oracle database in Django Web Framework. Django, the Python-based Web application structure, was initially intended to rearrange advancement of database-driven, news-arranged Web applications. From that point forward, it has advanced into a full-highlighted Web structure frequently picked to disentangle the improvement of complex, database-supported Web applications.

Django’s item social mapper (ORM) lies at the core of the structure, intervening between information models, which are Python classes you expand on the django.db.models.

Model class and hidden social database objects. After you have characterised information models, you will have the option to make, recover, update, and erase database information by means of the Python objects mapped to the items dwelling in the fundamental database.

The step by step procdure is as follows ,

Installation of Django Webframework:

In the event that you haven’t yet introduced Django, you can do it now,please click this link

To begin with, ensure you have Python 2.3 or later introduced. You can get Django from the Download page on the Django Software Foundation site at http://www.djangoproject.com/download/.

The establishment is clear. Simply unload the downloaded bundle, change registry into the one where you unloaded Django, and afterward run the accompanying order:

python setup.py install

The above command begins instaltion procedure that should take only a couple of moments. The least difficult approach to ensure that the establishment has been fruitful is through the Python intuitive mediator. In an intuitive translator meeting, simply enter the following command

import django

On the off chance that everything is good, you should see no error messages.

Now you are able to check out and make your first Django venture and an application inside it.

In Django, a task includes arrangement and applications for a specific Web website. Accordingly, a solitary undertaking may really incorporate different applications. For straightforwardness, however, the undertaking being made here will incorporate a solitary application.

In the first place, you may make a folde to be utilized for storing your Django projects, go into this folder from console , and afterward issue the following command:

django-admin.py
startproject myproj

Create an APP by using ,

manage.py startapp myapp

The above command shuold create the folder myapp and the accompanying four files inside it: __init__.py, models.py, views.py and tests.py. Once more, __init__.py is utilized here to make this index a Python bundle. Tests.py can be utilized to build a testsuite for your application. Also, you will utilize the staying two documents to characterize the application’s models and perspectives separately:

models.py is intended to contain models – Python classes that you expand on the django.db.models.Model class, and every one of which maps to a single database table.

views.py is intended to contain sees – Python works every one of which either restores a HttpResponse object with the substance to be shown on the mentioned page or raises a HTTP exemption.

The subsequent stage is to tie the recently made application to the venture. To do this, you should alter the settings.py record in the myproj envelope, annexing string ‘myproj.myapp’ to the INSTALLED_APPS tuple as follows:

INSTALLED_APPS
= (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'myproj.myapp'
)

You’re finished with the structure of the application skeleton. Before you can see the application in real life, however, some additional means are required. These means may shift contingent upon what you need your application to do, obviously.

For instance, you won’t have to place database data into the settings.py setup document and plan information models in case you’re dealing with a straightforward application that won’t connect with a database. By and large, nonetheless, you should take at any rate the accompanying five stages:

Indicate database data in settings.py

Create models

Create templates

Create Views

Configure URL pattrens in urls.py

Configuring Django to Interact with an Oracle Database: Django Web App Framework

Edit the settings.py to connect the database ,

DATABASE_ENGINE
= 'oracle' 
DATABASE_NAME
= 'Test' 
DATABASE_USER
= 'user' 
DATABASE_PASSWORD
= 'user' 
DATABASE_HOST
= 'localhost' 
DATABASE_PORT
= '1521'

Object-relation Mapping with Models

Django supports Object-relation mapping with models, where each model maps to a single database table and speaks to a Python class that subclasses the django.db.models.Model standard class.

The accompanying model represents how you may characterize a model on a current table. Right now, utilising the representatives table from HR, characterizing model fields just on chosen fields of the table. Open up and edit the models.py document in the myproj/myapp index,

we can create the model like this:

class
employees(models.Model):
employee_id =
models.IntegerField(primary_key=True)
first_name =
models.CharField(max_length=20, null = True)
last_name =
models.CharField(max_length=25)
email =
models.CharField(max_length=25)
class Meta:
db_table = "employees".
Using
Database-abstraction API
When you've finished building  the models,
you're prepared to proceed onward and manufacture sees in which those
models will be used. This is the place you can utilize Django
database-reflection API to make, recover, refresh and erase Python
objects (models) mapped to the articles in the hidden database. 
How about we make a straightforward view that
will get information from the workers and divisions database tables,
with the assistance of the models made in the previous area. In the
myproj/myapp catalog, open the views.py document and alter it as
follows:
#
Create your views here.
from
django.template import Context, loader
from
django.http import HttpResponse
from
myproj.myapp.models import employees, departments
def
index(request):
department_list =
departments.objects.exclude(manager__employee_id__exact =
None).order_by('manager__employee_id')
tmpl =
loader.get_template("index.html")
cont = Context({'departments':
department_list})
return
HttpResponse(tmpl.render(cont))
Transaction Management
As
a matter of course, Django utilizes the auto-COMMIT  transaction 
mode. This implies it promptly submits the progressions made by
information changing model strategies, for example, model.save and
model.delete, which you found in the former area. 
In any case, you can change this default conduct for a specific view work, utilising exchange decorators accessible by means of the django.db.transaction
module. You have the accompanying three choices: 
@transaction.autocommit
(default) 
@transaction.commit_on_success
@transaction.commit_manually
For
example, you might instruct Django to use a single transaction within
a view function and commit at the end only if the function returns
successfully, as follows:
from
django.http import HttpResponse
from
myproj.myapp.models import employees, departments
from
django.http import Http404
from
django.db import transaction
@transaction.commit_on_success
def
newdept(request, emp_id, dept_id, dept_name):
try:
new_dept =
departments(department_id = dept_id, department_name = dept_name,
manager = None)
new_dept.save()
emp =
employees.objects.get(employee_id__exact = emp_id)
new_dept.manager = emp
new_dept.save()
except employees.DoesNotExist:
raise Http404
return HttpResponse("The %s
department record has been inserted." %dept_name)

The newdept see work appeared above will consequently submit all the work done inside it just on the off chance that it returns effectively. On the off chance that an exemption is raised, all the progressions pending will be moved back.

Be that as it may, should you expel the embellishment put before the newdept see work, or supplant it with @transaction.autocommit, at that point the exchange conduct changes.

A HTTP 404 exemption will at present be produced upon inability to discover the representative determined. In any case, this time the change made by the first new_dept.save will be focused on the database quickly, bringing about an office record with the manager_id field unfilled.

It’s fascinating to take note of that the code in the previous posting could be essentially disentangled with the get_object_or_404 work characterised in the django.shortcuts module.

Here is the way the correction would resemble:

...
from
django.shortcuts import get_object_or_404 
@transaction.commit_on_success
def
newdept(request, emp_id, dept_name, dept_id):
new_dept = departments(department_id
= dept_id, department_name = dept_name, manager = None)
new_dept.save()
emp = get_object_or_404(employees,
employee_id__exact = emp_id)
new_dept.manager = emp
new_dept.save()
return HttpResponse("The %s
department record has been inserted." %dept_name )

Creating the Presentation Tier

As referenced, Django formats are intended to show data went to them from inside perspectives, utilising a django.template.Context object. Turning around to the list see work talked about in the Using Database-reflection API area prior, we should make format index.html utilised in that view.

In the first place, make an directory called templates inside the myapp registry. This is the place Django will search for templates as a matter of course. At that point, make index.html inside the myapp/templates registry.

The HTML code is as follows:

<h1>Managers of departments</h1>

<table
border = 1px cellpadding="3" style="font-family:Arial">
<tr>
<th>empNo</th>
<th>first
Name</th>
<th>first
Name</th>
<th>Email</th>
<th>Department
name</th>
</tr>
{%
for department in departments %}
<tr>
<td>{{department.manager.employee_id}}</td>
<td>{{department.manager.first_name}}</td>
<td>{{department.manager.last_name}}</td>
<td>{{department.manager.email}}</td>
<td>{{department.department_name}}</td>
{%
endfor %}
</table>

URL Dispatching

edit the url.py with following update

urlpatterns
= patterns('',
...
url(r'^myapp/',
include('myproj.myapp.urls')),
)
Then,
create an urls.py file in the myapp directory and insert the
following code there:
from
django.conf.urls.defaults import * 
from
myapp.views import index, newdept
urlpatterns
= patterns('',
url(r'^(?P<emp_id>\d+)/(?P<dept_name>\w+)/(?P<dept_id>\d+)/$'
, newdept),
url(r'^$',
index),
)

Using Django Development Web Server

Now we come to last step ,called testing phase of Django Application

manage.py runserver

Then it will display the output.

Conclusion

In this article , I discussed how to use oracle database with django web framework. Hope it will help you ,if you have any comments please share.

Scroll to Top