BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

6. Hello World Models and Database

django.png




Bookmark and Share





bogotobogo.com site search:




Models

In short, models are database tables represented in python code.

In modern web applications, the logic that Django's view performs involves interacting with a database. Behind the scenes, a database-driven web site connects to a database server, retrieves some data out of it, and displays that data on a web page. The site might also provide ways for site visitors to populate the database on their own.



Model class and Model instance

In general, each model maps to a single database table.

  1. Each model is a Python class that subclasses django.db.models.Model.
  2. Each attribute of the model represents a database field, and it's a column in the table.
  3. A model class == database table
  4. A model instance == database row
  5. Django gives us an automatically-generated database-access API.
  6. Django automatically takes care of things like primary keys if we do not explicitly manage them.



Setting up database

We normally need to edit settings.py which is a python module with module-level variables representing Django settings.

However, since the configuration uses SQLite by default, and SQLite is included in python, we don't need to install anything else to support our database.

Here is the DATABASES section of settings.py:

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

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

Initial_Tree.png

We need to create the tables in the database before we can use them. To do that, run the syncdb command which creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created:

$ python manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
...

Tree2.png

Now we have db.sqlite3 in our project as we can see at the top of the tree.




Writing a database web application

The first step of writing a database Web application in Django is to define our models - essentially, our database layout, with additional metadata.

Edit the HelloWorldApp/models.py file so that it should look like this:

from django.db import models

class Line(models.Model):                    # model - class    - table
    text = models.CharField(max_length=255)  # field - instance - row

Each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.

Each field is represented by an instance of a Field class - in our model, the CharField for character fields. This tells Django what type of data each field holds.

The name of each Field instance (text) is the field's name, in machine-friendly format. We'll use this value in our python code, and our database will use it as the column name.

Some Field classes have required arguments. CharField, for example, requires that we give it a max_length.




Creating database structure for a new model

We haven't created the database structure yet. The syncdb will do it for us:

$ python manage.py syncdb
Creating tables ...
Creating table HelloWorldApp_line
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

The syncdb command creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created. In our case, it's HelloWorldApp_line, which was the only new model that hasn't been created.




Playing with the model

Now, we've got our model.

Let's play with the model using interactive python shell which allows us to access python module in our App:

$ python manage.py shell
>>> from HelloWorldApp.models import Line
>>> Line.objects.all()
[]
>>> line = Line(text="Annabel Lee")
>>> line.save()
>>> Line
<class 'HelloWorldApp.models.Line'>
>>> Line.objects
<django.db.models.manager.Manager object at 0x24da7d0>

That's it. We've just created a new row in our database. Note that the Line is the class we defined earlier in HelloWorldApp/models.py.

If we want to query:

>>> Line.objects.all()
[<Line: Line object>]

We can see what's in the database using SQLite Database Browser:


SQLiteDatabaseBrowser.png

SQLiteDatabaseBrowser_BrowseData.png

Also, though not always possible and may not be a secure nor correct way, there is a way to see the database:

$ python manage.py sql HelloWorldApp
BEGIN;
CREATE TABLE "HelloWorldApp_line" (
    "id" integer NOT NULL PRIMARY KEY,
    "text" varchar(255) NOT NULL
)
;

COMMIT;



Updating the view

Now that we have a new model, we need to update our view, HelloWorldApp/views.py:

From:

from django.shortcuts import render_to_response

def foo(request,):
    return render_to_response("helloDJ/home.html", 
                               {"Testing" : "Django Template Inheritance ",
                               "HelloHello" : "Hello World - Django"})

To:

from django.shortcuts import render_to_response
from models import Line

def foo(request,):
    return render_to_response("helloDJ/home.html",
                               {"lines" : Line.objects.all()})



Updating the template

Also, we need to update our template (home.html) as well:

From:

{% extends "helloDJ/base.html" %}
{% block content %}
{{ Testing }}
{{ HelloHello }}
{% endblock %}                

To:

{% extends "helloDJ/base.html" %}

{% block content %}
<ul>
{% for line in lines %}
 <li style="color:{% cycle 'black' 'blue' 'green' %}"> {{ line.text }}</li>
{% endfor %}
</ul>
{% endblock %}



Web application with a database

Let's run the server, and see if it works:

$ python manage.py runserver

Type in http://localhost:8000/ or http://localhost:8000/HelloWorldApp/ into url box:


Browser_Database.png

OK! It works.

If we add more lines:


Browser_MoreLines.png



Note on urls.py

We talked about the url mapping in the previous chapter. Here, we should note that we tried two urls:

  1. http://localhost:8000/ is mapped by:
    url(r'^$', foo, name='home')
    
  2. http://localhost:8000/HelloWorldApp/ is mapped by:
    url(r'HelloWorldApp/$', foo),
    

For reference, here is the urls.py we're using:

from django.conf.urls import patterns, include, url
from HelloWorldApp.views import foo

#from django.contrib import admin
#admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    
    # url(r'^blog/', include('blog.urls')),

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

    url(r'^$', foo, name='home'),
    url(r'HelloWorldApp/$', foo),
)














Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Django 1.8



Introduction - Install Django and Project Setup

Creating and Activating Models

Hello World A - urls & views

Hello World B - templates

Hello World C - url dispatcher

Hello World D - Models and SQLite Database

MVC - Hello World

Hello World on a Shared Host A

Hello World on a Shared Host B

Hello World - Admin Site Setup

virtualenv

Creating test project on virtualenv

Test project's settings.py

Creating Blog app and setting up models

Blog app - syncdb A

Blog app - syncdb B

Blog app - views and urls

Blog app - templates

Blog app - class based templates

Image upload sample code - local host

Authentication on Shared Host using FastCGI

User Registration on Shared Host A

User Registration with a Customized Form on Shared Host B

Blogs on Shared Host

Serving Django app with uWSGI and Nginx

Image upload sample code - shared host

Managing (Deploying) Static files (CSS, Images, Javascript) on Shared Host

Forum application on a Shared Host

Django Python Social Auth : Getting App ID (OAuth2) - Facebook, Twitter, and Google

Django: Python social auth, Facebook, Twitter, and Google Auth

Django: Python social auth, Facebook, Twitter, and Google Auth with Static files

...

Django 1.8 hosted on Linode VPS ==>

1. Setup CentOS 7 hosted on VPS

1B. Setup CentOS 7 hosted on VPS (multi-domain hosting setup) - Name server and Zone File settings (from GoDaddy to Linode)

2. ssh login and firewall

3. Apache Install

4. Install and Configure MariaDB Database server & PHP

5. Install and Configure Django

6. Model

7. Model 2 : populate tables, list_display, and search_fields

8. Model 3 (using shell)

9. Views (templates and css)

10. Views 2 (home page and more templates)

11. TinyMCE

12. TinyMCE 2

13. ImageField/FileField : Serving image/video files uploaded by a user

14. User Authentication 1 (register & forms)

15. User Authentication 2 (login / logout)

16. User Authentication 3 (password reset) - Sent from Email (gmail) setup etc.

17. User Authentication 4 (User profile & @login_required decorator)

18. User Authentication 5 (Facebook login)

19. User Authentication 6 (Google login)

20. User Authentication 7 (Twitter login)

21. User Authentication 8 (Facebook/Google/Twitter login buttons)

22. Facebook open graph API timeline fan page custom tab 1

23. Facebook Open Graph API Timeline Fan Page Custom Tab 2 (SSL certificate setup)

24. Facebook open graph API timeline fan page custom tab 3 (Django side - urls.py, settings.py, and views.py)

...

A sample production site Django 1.8.7: sfvue.com / einsteinish.com ==>

A sample production app (sfvue.com) with virtualenv and Apache

2. Upgrading to Django 1.8.7 sfvue.com site sample with virtualenv and Apache

(*) Django 1.8.7 einsteinish.com site - errors and fixes

Django 1.8.12 pytune.com site - local with Apache mod_wsgi

Django 1.8.12 pytune.com site - local with Nginx and uWSGI

Django 1.8.12 pytune.com site - deploy to AWS with Nginx and uWSGI

Django Haystack with Elasticsearch and Postgres

Django Compatibility Cheat Sheet

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master