Python‎ > ‎django‎ > ‎

django.db


Definition
Django  works very well all types databases. However, python comes with pre-package  sqlite3 and no additional installation is required except to add import syntax.

Example
The registration form is created using models in which user is allowed to register for news letter. model.py fields are import into the forms.py using class Meta.

Window CMD  commands 

  • virtualenv pythonlake
  • cd  pythonlake
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py syncdb
  • python manage.py runserver

Files


mysite/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','myapp',
) 

mysite/urls.py

from django.contrib import admin
admin.autodiscover()
from myapp.views import Register, Response

urlpatterns = patterns('',
    # Examples:
    url(r'^$', Register),
     url(r'^thanks/$', Response),

    url(r'^admin/', include(admin.site.urls)),
)

myapp/admin.py

from django.contrib import admin

from .models import Reg

    class Meta:
        model=Reg

admin.site.register(Reg,RegAdmin)

myapp/models.py

from django.db import models
class Reg(models.Model):
    first_name=models.CharField(max_length=100)
    last_name=models.CharField(max_length=100)
    email=models.EmailField()
    

myapp/forms

from django import forms
from .models import Reg

class RegForm(forms.ModelForm):
    class Meta:
        model=Reg

myapp/views.py

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

def Register(request):

    form=RegForm(request.POST)
    if form.is_valid():
        save_form=form.save(commit=False)
        save_form.save()
        return HttpResponseRedirect('/thanks/')
    else:
        form=RegForm()

    return render(request, 'myapp\index.html', {'form':form})

def Response(request):
    return HttpResponse('Thanks for registering with us')

myapp/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<h1> Register for latest news</h1>

<form  action="" method="post">

    {%csrf_token%}

    {{form.as_p}}

    <input type="submit">

</form>

</body>
</html>






URLField is created through models and  viewed through index.html. 

Window CMD  commands 

  • virtualenv djangoschool
  • cd  djangoschool
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py syncdb
  • python manage.py runserver




mysite/setting.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles', 'myapp',
)

mysite/urls.py

from django.conf.urls import include, url

from myapp.views import ViewUrl
urlpatterns = [
    url(r'^', ViewUrl)
]


myapp/models.py

from django.db import models

class ModelUrl(models.Model):
    url=models.URLField()

    def __str__(self):
        return self.url


myapp/forms.py

from django import forms
from .models import ModelUrl

class FormUrl(forms.ModelForm):
    class Meta:
        model=ModelUrl
        fields=['url']


myapp/views.py

from django.shortcuts import render

from django.shortcuts import HttpResponseRedirectHttpResponse
from .forms import FormUrl

def ViewUrl(request):
    form=FormUrl(request.POST)
    if form.is_valid():
        form.save(commit=False)
        form.save()
        return HttpResponseRedirect('/thanks/')
    else:
        form=FormUrl
    return render(request, 'myapp/index.html',{'form':form})

def response(request):
    return HttpResponse("Thanks")

myapp/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<form  action="/thanks/" method="post">

    {%csrf_token%}

    {{form}}

    <input type="submit">

</form>

</body>
</html>

Localhost:8000



Database Query






Examples
Here in this example, the CharField  is used to store the data into the field.  The data is recorded and saved in models.py and retrieved and displayed through the views.py. 
 Steps for creating virtual environment, startproject, startapp, creating database, and migrating the data, and running server to check the app.
  • virtualenenv djangoschool
  • cd djangoschool
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • python manage.py migrate
  • python manage.py startapp dbapp
  • python manage.py makemigrations dbapp


mysite/settings,py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','dbapp',
)

mysite/urls.py

from django.conf.urls import include, url

from dbapp.views import Display

urlpatterns = [
    url(r'^', Display),
]

dbapp/models.py


    groups=(('male','0-40'),('female','0-40'))
    genderfield=models.CharField(max_length=50,choices=groups)

v=LongLife(genderfield="Casey")
v.save()

dbapp/views.py



from . models import LongLife

def Display (request):
    return HttpResponse(LongLife.objects.filter(genderfield="Casey").values())







Here, this examples, mydb.db database is created and in that database Table3 is created with Fields, name, email, telephone and income. The values are displayed through for loop by order of income in html file.
Steps for creating virtual environment, startproject, startapp, creating database, and migrating the data, and running server to check the app.
  • virtualenenv pythonlake
  • cd pythonlake
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • python manage.py migrate
  • python manage.py startapp mydb
  • python manage.py makemigrations mydb




mysite/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','mydb',
)

mysite/urls.py


from mydb.views import DataBase
urlpatterns = [
    url(r'^$', DataBase),
]

mydb/views.py

from django.shortcuts import render

import sqlite3

def DataBase (request):
    conn=sqlite3.connect('mydb.db')
    cursor=conn.cursor()
    cursor.execute('''CREATE TABLE table3(name text, phone text, email text, income text)''')
    cursor.execute('''INSERT INTO table3 VALUES(' Erica ', ' 571 402 2992 ', ' erica.steve@ibm.com ', '  180000 ')''')
    cursor.execute('''INSERT INTO table3 VALUES(' Strube ', ' 571 402 2212 ', ' marya_strube@care.com ', ' 890000 ')''')
    conn.commit()

    for row in cursor.execute('SELECT * FROM table3 ORDER BY income'):
        response=row

    return render(request, 'mydb\index.html', {'response':response} )

mydb/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Table3</title>
</head>
<body>

{{response}}

</body>
</html>