Python. Django. (Web Application Framework - WAF) PyCharm. (Integration Development Environment - IDE)

Similar documents
Linguistic Architecture

Graphene Documentation

Reminders. Full Django products are due next Thursday! CS370, Günay (Emory) Spring / 6

MIT AITI Python Software Development Lab DJ1:

Django urls Django Girls Tutorial

Tomasz Szumlak WFiIS AGH 23/10/2017, Kraków

django-scaffold Documentation

Django Phantom Theme Documentation

Webdev: Building Django Apps. Ryan Fox Andrew Glassman MKE Python

CE419 Web Programming. Session 15: Django Web Framework

Django starting guide

wagtailtrans Documentation

djangotribune Documentation

Building a Django Twilio Programmable Chat Application

django-baton Documentation

open-helpdesk Documentation

Technology modeling. Ralf Lämmel Software Languages Team University of Koblenz-Landau

django-baton Documentation

Django: Views, Templates, and Sessions

Python Schema Generator Documentation

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Django Admin Sortable Documentation

Django Test Utils Documentation

Django File Picker Documentation

MIT Global Startup Labs México 2013

Easy-select2 Documentation

django-contact-form Documentation

django-embed-video Documentation

django-auditlog Documentation

nacelle Documentation

STARCOUNTER. Technical Overview

django-allauth-2fa Documentation

Aldryn Installer Documentation

staff Documentation Release 1.2

django-embed-video Documentation

django-mama-cas Documentation

django-oauth2-provider Documentation

web.py Tutorial Tom Kelliher, CS 317 This tutorial is the tutorial from the web.py web site, with a few revisions for our local environment.

Djam Documentation. Release Participatory Culture Foundation

Python Project Documentation

django-model-utils Documentation

I hate money. Release 1.0


flask-dynamo Documentation

wagtailmenus Documentation

django-dynamic-db-router Documentation

django-embed-video Documentation

neo4django Documentation

Create-A-Page Design Documentation

Web Site Documentation Eugene School District 4J

Django Standalone Apps

Oracle SQL. murach s. and PL/SQL TRAINING & REFERENCE. (Chapter 2)

Django-CSP Documentation

django-private-chat Documentation

DJOAuth2 Documentation

Django File Picker Documentation

Runtime Dynamic Models Documentation Release 1.0

Module Road Map. 7. Version Control with Subversion Introduction Terminology

django-slim Documentation

Code::Blocks Student Manual

What is version control? (discuss) Who has used version control? Favorite VCS? Uses of version control (read)

Learning vrealize Orchestrator in action V M U G L A B

The Django Web Framework Part II. Hamid Zarrabi-Zadeh Web Programming Fall 2013

django-push Documentation

Django Extra Views Documentation

django-stored-messages Documentation

Unit E Step-by-Step: Programming with Python

CID Documentation. Release Francis Reyes

C1 CMS User Guide Orckestra, Europe Nygårdsvej 16 DK-2100 Copenhagen Phone

Tangent MicroServices Documentation

django-dajaxice Documentation

MapEntity Documentation

django-avatar Documentation

Bishop Blanchet Intranet Documentation

Imagery International website manual

Improved Web Development using HTML-Kit

정재성

Tablo Documentation. Release Conservation Biology Institute

DBNsim. Giorgio Giuffrè. 0 Abstract How to run it on your machine How to contribute... 2

CSCI 201 Lab 1 Environment Setup

Liquibase Version Control For Your Schema. Nathan Voxland April 3,

Zend Studio 3.0. Quick Start Guide

django-users2 Documentation

Accelerating Information Technology Innovation

django-model-report Documentation

django cms Documentation

git commit --amend git rebase <base> git reflog git checkout -b Create and check out a new branch named <branch>. Drop the -b

Kivy Designer Documentation

CuteFlow-V4 Documentation

Web2py Instant Admin Documentation

Django Image Tools Documentation

Lotus IT Hub. Module-1: Python Foundation (Mandatory)

The State of Python. and the web. Armin Ronacher

CSE 332: Data Structures and Parallelism Winter 2019 Setting Up Your CSE 332 Environment

django-gollum Documentation

A Tutorial on using Code::Blocks with Catalina 3.0.3

Django_template3d Documentation

Using SQL Developer. Oracle University and Egabi Solutions use only

wagtailmenus Documentation

django-mongonaut Documentation

Transcription:

Python Django (Web Application Framework - WAF) PyCharm (Integration Development Environment - IDE) Compiled and condensed notes from various online sources Gregg Roeten pg 1

Build Environment as of 09/10/2015 Windows 7 JetBrains PyCharm Community Edition 4.5.4 Build #PC0141.2569 Aug 28, 2015 JRE 1.8.0-51-b16x86 JVM: Java Hotspotserver Django 1.8.4 Python 3.4.3 Python SDKs, list of the interpreters available on your machine. PyCharm supports: Standard Python interpreters, IronPython, PyPy, Jython, Cpython Settings Project: MysiteProject Project Interpreter Package Version Latest Django 1.8 1.84 Pygments 2.0.2 2.0.2 pip 6.1.1 7.1.2 pudb 2015.2 2015.3 pytz 2015.2 2015.4 setuptools 15.2 18.3.1 urwid 1.3.0 1.3.0 pg 2

TABLE OF CONTENTS PYTHON... ERROR! BOOKMARK NOT DEFINED. PYTHON GENERAL NOTES... 6 PYTHON CODING STYLE FOR DJANGO... 9 Python style... 9 Template style... 9 View style... 9 Model style... 9 Use of django.conf.settings... 11 Miscellaneous... 11 DJANGO... 1 DJANGO WORKFLOW FOR URLS, TEMPLATES AND APPS... 12... 12 DJANGO PROCESS FLOW - BRIEF... 13 PROCESS FLOW - DETAILED... 14 User requests a page - How does Django process a request?... 14 Request reaches Request Middlewares... 14 handler send dispatcher signal request_started... 14 handler s _request_middleware... 14 ROOT_URLCONF... 14 _view_middleware... 15 Django template structure... 15 render template... 15 view - create an instance of django.http.httpresponse.... 15 exception... 15 Still no HttpResponse... 15 handler fires the dispatcher signal request_finished,... 15 GIT SETUP... 16 pg 3

WSGI WEB SERVER GATEWAY INTERFACE... 17 urls.py and views.py... 17 M = Model = data... 18 V = View = window on screen... 18 C = Controller... 18 CMS... 18 DATABASES... 19 SQLite... 19 Substring matching and case sensitivity... 19 Old SQLite and CASE expressions... 20 Using newer versions of the SQLite DB-API 2.0 driver... 20 Database is locked errors... 20 QuerySet.select_for_update() not supported... 20 pyformat parameter style in raw queries not supported... 20 Parameters not quoted in connection.queries... 20 MODELS... 22 Define Model... 22 Using Models... 22 ADMIN... 23 View... 23 DJANGO - HOW TO START AND DESIGN WITH DJANGO... 24 Normal Start Django... 24 DB Web app - Setup... 25 Configure and Create Database... 26 Create Python model... 29 Synchronizing the Database... 30 Configuring the Admin Interface... 30 API... 33 CUSTOMIZE USERS... 36 Creating an admin user... 36 Customize admin form... 36 TEMPLATES... 38 Web site /polls/34... 39 How to return an HttpResponse object... 40 How to differentiate the URL names between Multiple applications in a Django project... 41 pg 4

USE GENERIC VIEWS: LESS CODE IS BETTER... 44 pg 5

1. Why PyCharm A. Python Code Editor 1. Syntax highlighting 2. auto indent, code reformat 3. code completion 4. go to declaration, find usages 5. code analysis, inspection 6. realtime error highlighting 7. Rename refactoring allows to perform global code changes safely and instantly. Local changes within a file are performed in-place. Refactorings work in plain Python and Django projects. 8. Extract Method to break up longer methods, Extract Superclass, Push Up, Pull Down and Move to move the methods and classes. 9. B. Django IDE +JavaScript 1. IDE provides high-class capabilities for professional Web development with Django framework and Google App Engine. 2. coding assistance, navigation 3. breakpoints inside Django templates. Stop web appl where you need 4. Javascript debugger C. Run, Debug, Test 1. execute tasks from your manage.py file. Use 'Run manage.py task' action, enter a task name or event part of it and select the one you need. Debugger is started the same way. 2. Test Your Code: a test file, a single test class, a method, or all tests in a folder. 3. Create setup.py quickly using a special dialog and easily launch tasks defined inside setup.py 4. Python testing frameworks: Unittest, Doctest, Nosetest, py.test and Attest. 5. embedded local terminal 6. version control integration, Mercurial, Subversion, Git, CVS 7. Univided UI 8. Customizable UI 9. Issue Trackers integration, GitHub tracker 10. Plugins 11. SQL support for (Django, Flask) etc, SQL statements into source code. 12. PyCharm does not enable you to create databases, but provides facilities to manage and query them. 13. deployment servers-deploy your local applications to some remote server. https://confluence.jetbrains.com/display/pyh/pycharm+ide+and+python+plugin+for+intellij+idea 2. Deployment in PyCharm Don t be fooled Deployment in PyCharm is to deploy existing project on remote server. Upload project to a remote server. Running a copy on a separate server. pg 6

Supported Languages Python (Versions: 2.x, 3.x) Jython Cython IronPython PyPy Javascript CoffeScript TypeScript HTML/CSS Django/Jinja2 templates web2py templates Chameleon templates Gql LESS/SASS/SCSS/HAML Mako Puppet RegExp Rest SQL XML YAML Frameworks & Libraries supported Django Flask Google App Engine web2py Pyramid wxpython, PyQt, PyGTK SQLAlchemy... 3. Python general notes pg 7 Multithreading: No - single threaded: there are threads, but Global Interpreter Lock (GIL) allows just one Python thread to execute at any given moment of time (except the case when one of threads awaits for IO completion). everything is dynamic so Python doesn t need generics. dd your own tags (fields or methods) to nearly any object to change the behavior of third-party code. Python s decorators are definitely unbeatable in simplicity and flexibility. use *args, **kwargs - for static languages to enumerate/pass call arguments. with contexts in Python can process exceptions: exit method there gets

pg 8 information about thrown exception.

4. Python Coding style for Django A. Python style Use four spaces for indentation. Use underscores, for variable, function and method names (i.e. poll.get_unique_voters(), not poll.getuniquevoters). Use InitialCaps for class names (or for factory functions that return classes). Use convenience imports whenever available. For example, do this: from django.views.generic import View Don t do this: from django.views.generic.base import View B. Template style In Django template code, put one (and only one) space between the curly brackets and the tag contents. Do this: {{ foo }} Don t do this: {{foo}} C. View style In Django views, the first parameter in a view function should be called request. Do this: def my_view(request, foo): #... Don t do this: def my_view(req, foo): #... D. Model style Field names should be all lowercase, using underscores instead of camelcase. Do this: class Person(models.Model): first_name = models.charfield(max_length=20) last_name = models.charfield(max_length=40) Don t do this: class Person(models.Model): FirstName = models.charfield(max_length=20) Last_Name = models.charfield(max_length=40) The class Meta should appear after the fields are defined, with a single blank line separating the fields and the class definition. Do this: class Person(models.Model): first_name = models.charfield(max_length=20) last_name = models.charfield(max_length=40) pg 9 class Meta: verbose_name_plural = 'people'

Don t do this: class Person(models.Model): first_name = models.charfield(max_length=20) last_name = models.charfield(max_length=40) class Meta: verbose_name_plural = 'people' Don t do this, either: class Person(models.Model): class Meta: verbose_name_plural = 'people' first_name = models.charfield(max_length=20) last_name = models.charfield(max_length=40) If you define a str method (previously unicode before Python 3 was supported), decorate the model class with python_2_unicode_compatible(). The order of model inner classes and standard methods should be as follows (noting that these are not all required): All database fields Custom manager attributes class Meta def str () def save() def get_absolute_url() Any custom methods If choices is defined for a given model field, define each choice as a tuple of tuples, with an all-uppercase name as a class attribute on the model. Example: class MyModel(models.Model): DIRECTION_UP = 'U' DIRECTION_DOWN = 'D' DIRECTION_CHOICES = ( (DIRECTION_UP, 'Up'), (DIRECTION_DOWN, 'Down'), ) pg 10

E. Use of django.conf.settings Modules should not in general use settings stored in django.conf.settings at the top level (i.e. evaluated when the module is imported). The explanation for this is as follows: Manual configuration of settings (i.e. not relying on the DJANGO_SETTINGS_MODULE environment variable) is allowed and possible as follows: from django.conf import settings settings.configure({}, SOME_SETTING='foo') However, if any setting is accessed before the settings.configure line, this will not work. (Internally, settings is a LazyObject which configures itself automatically when the settings are accessed if it has not already been configured). So, if there is a module containing some code as follows: from django.conf import settings from django.core.urlresolvers import get_callable default_foo_view = get_callable(settings.foo_view)...then importing this module will cause the settings object to be configured. That means that the ability for third parties to import the module at the top level is incompatible with the ability to configure the settings object manually, or makes it very difficult in some circumstances. Instead of the above code, a level of laziness or indirection must be used, such as django.utils.functional.lazyobject, django.utils.functional.lazy() or lambda. F. Miscellaneous Mark all strings for internationalization;. Remove import statements that are no longer used when you change code. flake8 will identify these imports for you. If an unused import needs to remain for backwardscompatibility, mark the end of with # NOQA to silence the flake8 warning. Systematically remove all trailing whitespaces from your code as those add unnecessary bytes, add visual clutter to the patches and can also occasionally cause unnecessary merge conflicts. Some IDE s can be configured to automatically remove them and most VCS tools can be set to highlight them in diff outputs. Please don t put your name in the code you contribute. Our policy is to keep contributors names in the AUTHORS file distributed with Django not scattered throughout the codebase itself. Feel free to include a change to the AUTHORS file in your patch if you make more than a single trivial change. pg 11

Django workflow for Urls, Templates and Apps Customer input PC Browser HttpResponse to user Apache/ mod_python server, therefore Django handles HttpRequest from user Static info from customer urls layer url resolution - uses regular expressions to route requests file urls.py in folders MysiteProject, Application/templates MVC = Controller Apps layer Dynamic info from customer models.py and views.py in folder Application/template Use WSGI (Web Server Gateway Interface) wsgi.py modifies content MVC = View* WSGI Templates layer DIRS TEMPLATES in settings.py files.html in templates/admin information layout MVC =View (Python definition*) Database Project uses SQLite could use MySQL, etc MVC = Model pg 12

5. Django process flow - brief 1. User requests a page, running on Apache/mod_python therefore Django handles 2. HttpRequest sent to Request Middlewares (request function) which could manipulate or answer the HttpRequest 3. If no answer, then resolve URL with ROOT URLCONF in settings.py, match = MysiteProject.urls and send view function. 4. If match, handler calls View Middlewares (view function), which could manipulate or answer the HttpRequest 5. The view function may access data through models, must return HttpResponse or exception. 6. All model-to-db interactions are done via a manager 7. Views passed to the Template (base_site.html or index.html) for rendering 8. Template uses Filters and Tags (logic with html tags) to render the output 9. HttpResponse is sent to the Response Middlewares (get_response function) 10. The response is sent to the user s browser. For details of each step see below pg 13

6. Process flow - detailed pg 14 A. User requests a page - How does Django process a request? If Apache/mod_python is the server setup, in which case the request is handed to Django by mod_python creating an instance of django.core.handlers.modpython.modpythonhandler. The handler imports your Django settings file. B. Request reaches Request Middlewares 4 possible actions process: request, view, response and exception. _request_middleware is a list of the process_request methods (in each case these will be the actual methods, so they are directly callable) from any middleware classes which defined them. _view_middleware is a list of the process_view methods from any middleware classes, which defined them. _response_middleware is a list of the process_response methods from any middleware classes, which defined them. _exception_middleware is a list of the process_exception methods from any middleware classes, which defined them. C. handler send dispatcher signal request_started Then it instantiates a subclass of django.http.httprequest. Once an HttpRequest of some sort exists, the handler calls its own get_response method, passing the HttpRequest as the only argument. handler s _request_middleware does is loop through the handler s _request_middleware instance variable and call each method in that list, passing in the HttpRequest instance as an argument. get_response to return instance of django.http.httpresponse, to handler s _request_middleware More commonly, though, the middleware methods applied here simply do some processing and decide whether to add, remove or supplement attributes of the request. D. ROOT_URLCONF if Middlewares didn t send a response, the handler next tries to resolve the requested URL. It looks in the settings file for a setting called ROOT_URLCONF, and hands that, along with a base URL of /, as arguments to create an instance of django.core.urlresolvers.regexurlresolver, then calls the RegexURLResolver s resolve method with the requested URL path. The URL resolver follows a simple pattern. For each item in the urlpatterns list generated by the URL configuration file specified by the ROOT_URLCONF setting, it checks whether the requested URL path matches that item s regular expression; if so, there are two options: If the item has a call to include, the resolver chops off the bit of the URL that matched, moves to the URL configuration file specified by the include and begins iterating over the items in its urlpatterns list. Depending on the depth and modularity of your URL hierarchy, this may be repeated several times. Otherwise, the resolver returns three items: the view function specified by the matched item, a list of non-named matched groups from the URL (to be used as positional arguments for the view) and a dictionary of keyword arguments, built from a combination of any named matched groups in the URL and any extra keyword arguments specified in that line in the URLConf.

If no matches are found, the resolver raises the exception django.core.urlresolvers.resolver404, a subclass of the exception django.http.http404. We ll get to how that s handled a little later on. _view_middleware knows the view function and what arguments to pass to it, the handler looks at its _view_middleware list, and calls each method in that list, passing the HttpRequest, the view function, the list of positional arguments for the view and the dictionary of keyword arguments for the view. Again, it s possible for middleware to intervene at this stage and force the handler to return immediately. E. Django template structure base_site.html extends admin/base_site.html, which is in PROJECT_DIR/template path index.html extends admin/base_site.html, which is in PROJECT_DIR/PoolsApplications/template path render template Loading the template to be rendered; is handled by the function django.template.loader.get_template, The get_template function returns an instance of django.template.template, which is an object containing the parsed template and methods for using it. The return value of the Template s render method is a string, which is the concatenation of the return values of the render methods of all the Template s constituent Nodes, called in the order in which they occur in the Template. F. view - create an instance of django.http.httpresponse. exception get_response passing the HttpRequest and the exception as arguments. one of those methods may instantiate and returns an HttpResponse. Still no HttpResponse The view might not have returned a value. The view might have raised an exception that none of the middleware was able to deal with. A middleware method that was trying to deal with an exception might have raised a new exception itself. Default get_response sends Http404 If DEBUG is False, page_not_found, If the DEBUG setting is True, technical_500_response, G. handler fires the dispatcher signal request_finished, which is the absolute last call for anything that wanted to execute during the current request? clean up free any resources pg 15

Git setup create a working directory & navigate to it $ mkdir custom-reg-tutorial $ cd custom-reg-tutorial download the git repo # don't forget the. at the end! $ git clone https://github.com/launchsaas/custom-reg-tutorial. git for version control GitHub for project management 1. GitHub's "Issues" for the following: 1. bug tracking 2. feature requests 3. planned features 4. release/version management git-flow for git workflow py.test for unit testing https://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/ pg 16

WSGI Web Server Gateway Interface WSGI is the Web Server Gateway Interface. A specification describes how a web server communicates with web applications, and how web applications can be chained together to process one request. WSGI is a Python standard Use a Web app framework. They all support WSGI at this point, which means you need to worry about configuration and deployment of your app, and nothing else. urls.py and views.py focus on urls.py and views.py that will process your urls and return the info you want as an http response. e.g. urls.py urlpatterns += patterns ('myapp.views', ) url (r'^getstuff/$', getstuff ), in views.py def getstuff (request): do whatever in python return HttpResponse (stuff to return) pg 17

Python s web service framework is based on MVC 1. Django uses MVC (Model View Controller) MVC (Model View Controller) used as the Design pattern, for definitions see below. different from standard MVC definition Framework itself, mechanism that sends a request to the appropriate view M = Model = data Database layer Encapsulates application state Responds to state queries Notifies view of changes V = View = window on screen Different Django View and standard MVC view selects which data to display and how to display it renders the models Requests updates Allows controller to select view handled by views.py and templates directory C = Controller Defines application behavior, based on user input, access model as needed by following the URLConf and calling the appropriate Python function for the given URL Isolates logic (Model) from the user interface(view) CMS Django is not a CMS, or any sort of turnkey product in and of itself. It s a Web framework; it s a programming tool that lets you build Web sites. Django version Python versions 1.4 2.5, 2.6, 2.7 1.7, 1.8 2.7 and 3.2, 3.3, 3.4 1.9 2.7, 3.3, 3.4, 3.5 pg 18

2. Databases You don't need to use database in Django projects. Django comes with some standardized architecture that follows MVC pattern (or MVT as sometimes described). This includes models, views, url dispatching, templates, etc. Probably you need to do following things to accomplish your task: create url definition in urls.py to some Django view write Django view that call somehow your API and displays result as a web page you don't need models and database at all Small project usually consists of the web server and "back-end" code will run on the same system (initially, Windows system) as the UI. creation of a basic poll application. It ll consist of two parts: A public site that lets people view and vote in them. An admin site that lets you add, change and delete polls. If you plan to use Django s manage.py migrate command to automatically create database tables for your models (after first installing Django and creating a project), you ll need to ensure that Django has permission to create and alter tables in the database you re using; if you plan to manually create the tables, you can simply grant Django SELECT, INSERT, UPDATE and DELETE permissions. After creating a database user with these permissions, you ll specify the details in your project s settings file, see DATABASES for details. If you re using Django s testing framework to test database queries, Django will need permission to create a test database. H. SQLite SQLite provides an excellent development alternative for applications that are predominantly read-only or require a smaller installation footprint. As with all database servers, though, there are some differences that are specific to SQLite that you should be aware of. Substring matching and case sensitivity For all SQLite versions, there is some slightly counter-intuitive behavior when attempting to match some types of strings. These are triggered when using the iexact or contain filters in Querysets. The behavior splits into two cases: 1. For substring matching, all matches are done case-insensitively. That is a filter such as filter (name contains="aa") will match a name of "Aabb". 2. For strings containing characters outside the ASCII range, all exact string matches are performed case-sensitively, even when the case-insensitive options are passed into the query. Therefore, the iexact filter will behave exactly the same as the exact filter in these cases. Some possible workarounds for this are documented at sqlite.org, but they aren t utilized by the default SQLite backend in Django, as incorporating them would be fairly difficult to do robustly. Thus, Django exposes the default SQLite behavior and you should be aware of this when doing case-insensitive or substring filtering. pg 19

Old SQLite and CASE expressions SQLite 3.6.23.1 and older contains a bug when handling query parameters in a CASE expression that contains an ELSE and arithmetic. SQLite 3.6.23.1 was released in March 2010, and most current binary distributions for different platforms include a newer version of SQLite, with the notable exception of the Python 2.7 installers for Windows. Using newer versions of the SQLite DB-API 2.0 driver Django will use a pysqlite2 module in preference to sqlite3 as shipped with the Python standard library if it finds one is available. This provides the ability to upgrade both the DB-API 2.0 interface and SQLite 3 itself to versions newer than the ones included with your particular Python binary distribution, if needed. Database is locked errors SQLite is meant to be a lightweight database, and thus can t support a high level of concurrency. OperationalError: database is locked errors indicate that your application is experiencing more concurrency than SQLite can handle in default configuration. This error means that one thread or process has an exclusive lock on the database connection and another thread timed out waiting for the lock the be released. Python s SQLite wrapper has a default timeout value that determines how long the second thread is allowed to wait on the lock before it times out and raises the OperationalError: database is locked error. If you re getting this error, you can solve it by: Switching to another database backend. At a certain point SQLite becomes too lite for real-world applications, and these sorts of concurrency errors indicate you ve reached that point. Rewriting your code to reduce concurrency and ensure that database transactions are short-lived. Increase the default timeout value by setting the timeout database option: 'OPTIONS': { #... 'timeout': 20, #... } This will simply make SQLite wait a bit longer before throwing database is locked errors; it won t really do anything to solve them. QuerySet.select_for_update() not supported SQLite does not support the SELECT... FOR UPDATE syntax. Calling it will have no effect. pyformat parameter style in raw queries not supported For most backends, raw queries (Manager.raw() or cursor.execute()) can use the pyformat parameter style, where placeholders in the query are given as '%(name)s' and the parameters are passed as a dictionary rather than a list. SQLite does not support this. pg 20 Parameters not quoted in connection.queries sqlite3 does not provide a way to retrieve the SQL after quoting and substituting the parameters. Instead, the SQL in connection.queries is rebuilt with a simple string

pg 21 interpolation. It may be incorrect. Make sure you add quotes where necessary before copying a query into an SQLite shell.

3. Models single, definitive source of information about your data. contains essential fields behaviors of the data you re storing. model maps to a single database table. A. Define Model ex. application named polls, contains file models.py This example model defines a Person, which has a first_name and last_name: from django.db import models class Person(models.Model): first_name = models.charfield(max_length=30) last_name = models.charfield(max_length=30) first_name and last_name are fields of the model. Each field is specified as a class attribute, each attributes maps to a database column. model would create a database table like this: CREATE TABLE myapp_person ( "id" serial NOT NULL PRIMARY KEY, "first_name" varchar(30) NOT NULL, "last_name" varchar(30) NOT NULL ); B. Using Models Tell Django how to use models mysite\mysite\settings.py function INSTALLED_APPS add name of module that contains your models.py ex polls, run manage.py migrate run manage.py makemigrations C. Fields Example: polls\models.py file from django.db import models pg 22 class Musician(models.Model): first_name = models.charfield(max_length=50)

last_name = models.charfield(max_length=50) instrument = models.charfield(max_length=100) class Album(models.Model): artist = models.foreignkey(musician) name = models.charfield(max_length=100) release_date = models.datefield() num_stars = models.integerfield() 4. Admin Select an object then change it let s you write and register actions, simple functions that get called with a list of objects A. View All Django wants is that HttpResponse. Alternatively, an exception. Each view is responsible for doing one of two things: returning an HttpResponse object containing the content for the requested page, or raising an exception such as Http404. The rest is up to you. Your view can read records from a database, or not. use a template system such as Django s or a third-party Python template system or not. generate a PDF file, output XML, create a ZIP file on the fly, anything you want, using whatever Python libraries you want. view is a type of Web page in your Django application that generally serves a specific function and has a specific template. For example, in a blog application, you might have the following views: Blog homepage displays the latest few entries. Entry detail page permalink page for a single entry. Year-based archive page displays all months with entries in the given year. Month-based archive page displays all days with entries in the given month. Day-based archive page displays all entries in the given day. Comment action handles posting comments to a given entry. In our poll application, we ll have the following four views: Question index page displays the latest few questions. Question detail page displays a question text, with no results but with a form to vote. Question results page displays results for a particular question. Vote action handles voting for a particular choice in a particular question. In Django, web pages and other content are delivered by views. Each view is represented by a simple Python function (or method, in the case of class-based views). Django will choose a view by examining the URL that s requested (to be precise, the part of the URL after the domain name). pg 23

Python - 2 methods to start and design with Python Method 1 Use wordpad for editing.py files Use Windows command prompt to run python commands, like server, etc Method 2 - PyCharm Preferred method PyCharm background and setup PyCharm supports Django including Dedicated project type ability to run tasks from the manage.py utility Django templates support (syntax and error highlighting, code completion, navigation, completion for block names, resolve and completion for custom tags and filters, and quick documentation for tags and filters). Ability to create templates from usage. Ability to debug Django templates. Live templates (snippets) for the quick development of Django templates. Run/debug configuration for Django server. Navigation between views and templates. Code insight support for Django ORM. Code completion and resolve in Start JetBrains - PyCharm Community Edition 4.0.6 Open project pg 24

Normal Start for Django in PyCharm open Terminal part of window and startup server python manage.py runserver project directory has manage.py Django Python web server address http://127.0.0.1:8000/ pg 25 DB Web app - Setup python -c "import Django; print(django.get_version())" Python 3.3 latest release, Django 1.7, 1.8 is beta

django-admin startproject mysite creates project mysite and directory structure mysite/ manage.py mysite/ init.py settings.py urls.py wsgi.py File Definitions in the Project view mysite directory is a container for your project. In the Project view it is denoted with bold font. manage.py: This is a command-line utility that lets you interact with your Django project. The nested directory mysite is the actual Python package for your project. mysite/_init_.py: This empty file tells Python that this directory should be considered a Python package. mysite/settings.py: This file contains configuration for your Django project. mysite/urls.py: This file contains the URL declarations for your Django project. a table of contents of your Django-powered site. mysite/wsgi.py: This file defines an entry-point for WSGI-compatible web servers to serve your project. See Appendix How to deploy with WSGI for more details. polls/models.py: In this file, we'll create models for our application. polls/views.py: In this file, we'll create views. templates directory is by now empty. It should contain the template files. The nested directory migrations contains by now only the package file _init_.py, but will be used to propagate the changes you make to your models (adding a field, deleting a model, etc.) into your database schema. Read the migrations description here. Always remember we have two mysites, designated inner and outer The outer mysite/ root directory is just a container for your project. rename it to anything you like. The inner mysite/ directory are the actual Python package for your project. Used to import anything inside it (e.g. mysite.urls). pg 26 Configure and Create Database edit mysite/settings.py select the project tool window and press F4. select DATABASES var click Ctrl+F, ENGINE - add name of DB set TIME_ZONE to your time zone. Database Setup if you want a DB other than SQLite If you wish to use another database, install the appropriate database bindings, and change the following keys in the DATABASES 'default' item to match your database connection settings: ENGINE Either 'django.db.backends.sqlite3', 'django.db.backends.postgresql_psycopg2', 'django.db.backends.mysql', or 'django.db.backends.oracle'. Other backends are also available. NAME The name of your database. If you re using SQLite, the database will be a file on your computer; in that case, NAME should be the full absolute path, including filename, of that file. The default value, os.path.join(base_dir, 'db.sqlite3'), will

store the file in your project directory. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DATABASE_PATH, } } If you are not using SQLite as your database, additional settings such as USER, PASSWORD, HOST must be added. Note If you re using PostgreSQL or MySQL, make sure you ve created a database by this point. Do that with CREATE DATABASE database_name ; within your database s interactive prompt. If you re using SQLite, you don t need to create anything beforehand - the database file will be created automatically when it is needed. Used in this example. DATABASE_PATH = os.path.join(project_path, 'rango.db') Here, we have defined the default database to use the SQLite Django backend. This provides us with access to the lightweight python database, SQLite, which is great for development purposes. Set is the NAME key/value pair, which we have set to DATABASE_PATH. For SQLite databases, the remaining keys of USER, PASSWORD, HOST and PORT are not required and can thus be safely removed. python manage.py migrate creates DB python manage.py runserver starts development server, lightweight web server written in Python, incl in Django for rapid dev, no need to config Apache no cursor until you stop server Launch Django Server in PyCharm python manage.py startapp polls Actually creates app If you choose sqlite3, just verify auto user credentials, port and host just launch the runserver task of the manage.py utility: press Ctrl+Alt+R, and enter task name in the pop-up frame: add an application to a project, run the startapp task of the manage.py utility pg 27

(Tools Run manage.py task - startapp on the main menu). in browser http://127.0.0.1:8000/ works Each application you write in Django consists of a Python package Diff Projects vs. apps app is a Web application that does something e.g., a Weblog system, a database of public records or a simple poll app. project is a collection of configuration and apps for a particular Web site. A project can contain multiple apps. An app can be in multiple projects. Performing administrative functions First thing, create a superuser. To do that, type the superuser command in the manage.py console, specify your email address, and password: server not running python manage.py createsuperuser smooth smooth@smooth.com smooth pg 28

smooth Create Python model Change your models (in models.py). Run python manage.py makemigrations to create migrations for those changes Run python manage.py migrate to apply those changes to the database. Use separate commands to make and apply migrations to make your development easier, they re also useable by other developers and in production. Create the two initial data models for the Mysite application. Django s object relational mapping (ORM) functions Django encapsulates databases tables through models. Essentially, a model is a Python object that describes your data model/table. Instead of directly working on the database table via SQL, all you have to do is manipulate the corresponding Python object. Edit polls/models.py In mysite/models.py, we will define two classes - both of which must inherit from django.db.models.model. The two Python classes will be the definitions for models representing Questions and Choices. Define the Question and Choice models fields as follows: class Question(models.Model): question_text = models.charfield(max_length=200) pub_date = models.datetimefield('date published') def unicode (self): return self.name class Choice(models.Model): question = models.foreignkey(question) choice_text = models.charfield(max_length=200) votes = models.integerfield(default=0) ForeignKey, a field type that allows us to create a one-to-many relationship. pg 29 Some of the most commonly used are listed below.

CharField, a field for storing character data (e.g. strings). Specify max_length to provide a maximum number of characters the field can store. URLField, much like a CharField, but designed for storing resource URLs. You may also specify a max_length parameter. IntegerField, which stores integers. DateField, which stores a Python datetime.date. Synchronizing the Database Our models are defined, Django needs to create table in our database SQLlite. $ python manage.py syncdb Synchronize the DB, converts the Django models into SQL tables. $ python manage.py shell run from within your Django project s root directory aid for debugging purposes This will start an instance of the Python interpreter and load in your project s settings for you. Configuring the Admin Interface Activate Model web-based administrative interface that allows us to browse and edit data stored within our models and corresponding database tables. configure the admin interface then access it. mysite/settings.py change the INSTALLED_APPS setting to include the 'polls' pg 30 INSTALLED_APPS = [ ] 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', Now Django knows to include the polls app. table django_admin_log is created urls.py file. URL pattern /admin/ points to the admin.site.urls module

from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^rango/', include('rango.urls')), url(r'^admin/', include(admin.site.urls)), # ADD THIS LINE ) Django admin application needs to know which models we wish to make available to the admin interface. admin.py create a new python file in mysite application directory called admin.py. Add from django.contrib import admin from mysite.models import Question, Choice admin.site.register(question) admin.site.register(choice) This will register the models with the admin interface. I start or restart the Django development server and visit: Terminal python manage.py runserver smooth smooth http://127.0.0.1:8000/admin/. Enter the superuser username and password (created when setting up database) Following should be displayed pg 31

The Django admin interface. Note the Mysite category, and the two models contained within. python manage.py syncdb python manage.py makemigrations polls Django now sees changes or additions made stored as a migration. To be physically migrated later python manage.py sqlmigrate polls 0001 sqlmigrate doesn t run the migration on your DB, Only prints to the screen Double check what Django will do. The sqlmigrate command takes migration names and returns their SQL Migrations for 'polls': 0001_initial.py: - Create model Choice - Create model Question - Add field question to choice output after command BEGIN; -- pg 32

-- Create model Choice -- CREATE TABLE "polls_choice" ( "id" serial NOT NULL PRIMARY KEY, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL ); -- -- Create model Question -- CREATE TABLE "polls_question" ( "id" serial NOT NULL PRIMARY KEY, "question_text" varchar(200) NOT NULL, "pub_date" timestamp with time zone NOT NULL ); -- -- Add field question to choice -- ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL; ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT; CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id"); ALTER TABLE "polls_choice" ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id" FOREIGN KEY ("question_id") REFERENCES "polls_question" ("id") DEFERRABLE INITIALLY DEFERRED; COMMIT; sqlmigrate table names auto generated combining name of app- polls and lower case name of the models - question and choice primary keys auto gen database field types auto set python manage.py migrate Actual migrate command, Migrate any changes/tables created to DB synchronizes the changes you made to your models with the schema in the database. python manage.py check Check DB for errors API python manage.py shell manage.py shell sets the DJANGO_SETTINGS_MODULE environment variable, gives Django the Python import path to your mysite/settings.py file. > from polls.models import Question, Choice no information printed after entry # Import the model classes we just wrote. # No questions are in the system yet. > Question.objects.all() [] # Create a new Question. # Support for time zones is enabled in the default settings file, so pg 33

# Django expects a datetime with tzinfo for pub_date. Use timezone.now() # instead of datetime.datetime.now() and it will do the right thing. > from django.utils import timezone > q = Question(question_text="What's new?", pub_date=timezone.now()) > q.save() # Save the object into the database. You have to call save() explicitly. > q.id # Now it has an ID. Note that this might say "1L" instead of "1", depending # on which database you're using. That's no biggie; it just means your # database backend prefers to return integers as Python long integer # objects. 1 > q.question_text # Access model field values via Python attributes. "What's new?" > q.pub_date datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<utc>) > q.question_text = "What's up?" # Change values by changing the attributes, then calling save(). > q.save() > Question.objects.all() [<Question: Question object>] # objects.all() displays all the questions in the database. Wait a minute. <Question: Question object> is, utterly, an unhelpful representation of this object. Let s fix that by editing the Question model (in the polls/models.py file) and adding a unicode () method to both Question and Choice: It s important to add unicode () methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects representations are used throughout Django s automatically generated admin. polls/models.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): #... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) python manage.py shell new Python interactive shell pg 34

> from polls.models import Question, Choice # Make sure our str () addition worked. > Question.objects.all() [<Question: What's up?>] # Django provides a rich database lookup API that's entirely driven by # keyword arguments. > Question.objects.filter(id=1) [<Question: What's up?>] > Question.objects.filter(question_text startswith='what') [<Question: What's up?>] > from django.utils import timezone # Get the question that was published this year > current_year = timezone.now().year > Question.objects.get(pub_date year=current_year) <Question: What's up?> > Question.objects.get(id=2) # Request an ID that doesn't exist, this will raise an exception Traceback (most recent call last):... DoesNotExist: Question matching query does not exist. > Question.objects.get(pk=1) <Question: What's up?> # Lookup by a primary key is the most common case, so Django provides a # shortcut for primary-key exact lookups. # The following is identical to Question.objects.get(id=1). > q = Question.objects.get(pk=1) # Make sure our custom method worked. > q.was_published_recently() True > q = Question.objects.get(pk=1) # Give the Question a couple of Choices. The create call constructs a new # Choice object, does the INSERT statement, adds the choice to the set # of available choices and returns the new Choice object. Django creates # a set to hold the "other side" of a ForeignKey relation # (e.g. a question's choice) which can be accessed via the API. > q.choice_set.all() Display any choices from the related object set -- none so far. [] # Create three choices. > q.choice_set.create(choice_text='not much', votes=0) <Choice: Not much> > q.choice_set.create(choice_text='the sky', votes=0) <Choice: The sky> pg 35

> c = q.choice_set.create(choice_text='just hacking again', votes=0) Choice objects have API access to their related Question objects. > c.question <Question: What's up?> # And vice versa: Question objects get access to Choice objects. > q.choice_set.all() [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] > q.choice_set.count() # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want; there's no limit. # Find all Choices for any question whose pub_date is in this year # (reusing the 'current_year' variable we created above). > Choice.objects.filter(question pub_date year=current_year) [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>] # Let's delete one of the choices. Use delete() for that. > c = q.choice_set.filter(choice_text startswith='just hacking') > c.delete() 5. Customize Users A. Creating an admin user Django entirely automates creation of admin interfaces for models python manage.py createsuperuser already done Tell the admin that Question objects have an admin interface. open the polls/admin.py file, and edit it to look like this: from django.contrib import admin from.models import Question admin.site.register(question) Forms automatically generated from the Question Model B. Customize admin form re-ordering the fields on the edit form. Change admin.site.register(question) line with: open file polls/admin.py pg 36 from django.contrib import admin

from.models import Question class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date']}), ] admin.site.register(question, QuestionAdmin) You ll follow this pattern create a model admin object, then pass it as the second argument to admin.site.register() any time you need to change the admin options for an object. This particular change above makes the Publication date come before the Question field: collapse- long form need to hide fields. click (show) to see fields class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] Adding related objects Add choices to Question admin page Register Choice with admin like Question was registered in polls/admin.py from django.contrib import admin from.models import Choice, Question #... admin.site.register(choice) python manage.py runserver now have choice and question in admin page ForeignKey is represented in the admin as a <select> box. Add Another link next to Question. Every object with a ForeignKey relationship to another gets this for free. When you click Add Another, you ll get a popup window with the Add question form. If you add a question in that window and click Save, Django will save the question to the database and dynamically add it as the selected choice on the Add choice form you re looking at Add several Choices directly instead of one at a time admin.py Remove register() call, add ChoiceInline pg 37

admin.site.register(question) admin.site.register(choice) class ChoiceInline(admin.StackedInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), ] inlines = [ChoiceInline] admin.site.register(question, QuestionAdmin) more compact form polls/admin.py class ChoiceInline(admin.TabularInline): display individual fields. By default, Django displays the str() of each object. But sometimes it d be more helpful if we could display individual fields. To do that, use the list_display admin option, which is a tuple of field names to display, as columns, on the change list page for the object: To do that, use the list_display admin option, which is a tuple of field names to display, as columns, on the change list page for the object: polls/admin.py class QuestionAdmin(admin.ModelAdmin): #... list_display = ('question_text', 'pub_date', 'was_published_recently') filter sidebar to filter changes list in the pub_date field: polls/admin.py list_filter = [ pub_date ] search_fields = ['question_text'] search capability 6. Templates in project directory (one with manage.py) create templates directory mysite/settings.py change DIRS :[], to DIRS :[ os.path.join(base_dir, 'templates')], create admin directory inside templates copy template = admin/base_site.html into the new admin directory Customize template = Override template, change web page title to S K edit file base_site.html H:\My Documents\- Soft langs, WAP, websites, Frameworks\- Python, Django\mysite\templates\admin\base_site.html note: django.contrib.admin is an application Customize admin index page admin/index.html. (Do the same as with admin/base_site.html in the previous section pg 38

copy it from the default directory to your custom template directory.) Edit the file, and you ll see it uses a template variable called app_list. That variable contains every installed Django app. Instead of using that, you can hard-code links to object-specific admin pages in whatever way you think is best. polls/views.py change HttpResponse map it to a URL using polls/urls.py create polls/urls.py from django.conf.urls import url from. import views urlpatterns = [ url(r'^$', views.index, name='index'), ] point the root URLConf to the polls.urls create mysite/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), ] Web site /polls/34 Django will load the mysite.urls because it s pointed to by the ROOT_URLCONF setting. It finds the variable named urlpatterns and traverses the regular expressions in order. They include() functions we are using simply reference other URLConf. Note that the regular expressions for the include() functions don t have a $ (end-of-string match character) but rather a trailing slash. Whenever Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLConf for further processing. The idea behind include() is to make it easy to plug-and-play URLs. Since polls are in their own URLConf (polls/urls.py), they can be placed under /polls/, or under /fun_polls/, or under /content/polls/, or any other path root, and the app will still work. Here s what happens if a user goes to /polls/34/ in this system: Django will find the match at '^polls/' Then, Django will strip off the matching text ("polls/") and send the remaining text "34/" to the polls.urls URLConf for further processing which matches r'^(?p<question_id>[0-9]+)/$' resulting in a call to the detail() view like so: detail(request=<httprequest object>, question_id='34') C. Django s template system to separate the design from Python use Django s template system to separate the design from Python by creating a template that the view can use. pg 39