Web Frame Work-Django
Web Frame Work-Django
Web Frame Work-Django
The majority of Web frameworks are exclusively server-side technology, although, with the
increased prevalence of AJAX, some Web frameworks are beginning to include AJAX code that
helps developers with the particularly tricky task of programming (client-side) the user's
browser. At the extreme end of the client-side Web Frameworks is technology that can use the
web browser as a full-blown application execution environment (a la gmail for example): see
Web Browser Programming for details.
As a developer using a framework, you typically write code which conforms to some kind of
conventions that lets you "plug in" to the framework, delegating responsibility for the
communications, infrastructure and low-level stuff to the framework while concentrating on the
logic of the application in your own code. This "plugging in" aspect of Web development is
often seen as being in opposition to the classical distinction between programs and libraries, and
the notion of a "mainloop" dispatching events to application code is very similar to that found in
GUI programming.
Generally, frameworks provide support for a number of activities such as interpreting requests
(getting form parameters, handling cookies and sessions), producing responses (presenting data
as HTML or in other formats), storing data persistently, and so on. Since a non-trivial Web
application will require a number of different kinds of abstractions, often stacked upon each
other, those frameworks which attempt to provide a complete solution for applications are often
known as full-stack frameworks in that they attempt to supply components for each layer in the
stack.
Many frameworks now provide an element of customization in their support for the above
activities and abstractions, utilizing components in that they provide abstractions only for certain
specific things. As a result, it can be possible for you to build your own full-stack framework
almost entirely from existing components.
These are the most popular high-level frameworks. Many of them include components listed on
the WebComponents page.
Latest
Latest
Name update description
version
date
The Web framework for perfectionists (with deadlines). Django
makes it easier to build better Web apps more quickly and with
less code. Django is a high-level Python Web framework that
2019-
Django 2.2.3 encourages rapid development and clean, pragmatic design. It lets
07-01
you build high-performing, elegant Web applications quickly.
Django focuses on automating as much as possible and adhering
to the DRY (Don't Repeat Yourself) principle. See Django
the rapid Web development webframework you've been looking
for. Combines SQLAlchemy (Model) or Ming (MongoDB
Model), Kajiki (View), Repoze and ToscaWidgets2. Create a
database-driven, ready-to-extend application in minutes. All with
2019-
TurboGears 2.4.1 designer friendly templates, easy AJAX on the browser side and
09-03
on the server side, with an incredibly powerful and flexible Object
Relational Mapper (ORM), and with code that is as natural as
writing a function. After reviewing the Documentation, check out
the Tutorials
* Python 2.6 to 2.7, Python 3.x friendly (compile but not tested no
2019-
web2py 2.18.5 support yet) * All in one package with no further dependencies.
04-07
Development, deployment, debugging, testing, database
administration and maintenance of applications can be done via
the provided web interface, but not required. * web2py has no
configuration files, requires no installation, can be run off a USB
drive. * web2py uses Python for the Model, View and the
Controller * Built-in ticketing system to manage errors *
Internationalization engine and pluralisation, caching system *
Flexible authentication system (LDAP, MySQL, janrain etc) *
NIX(Linux, BSD), Windows, Mac OSX, tested on EC2,
Webfaction * works with MySQL, PostgreSQL, SQLite , Firebird,
Oracle, MSSQL and the Google App Engine via an ORM
abstraction layer. * Includes libraries to handle HTML/XML,
RSS, ATOM, CSV, RTF, JSON, AJAX, XMLRPC, WIKI
markup. * Production ready, capable of upload/download of very
large files * Emphasis on backward compatibility.
See below for some other arguably less popular full-stack frameworks!
Latest
Latest
Name update description
version
date
a semantic web application framework featuring a query
2018-
CubicWeb 3.26.4 language, a selection+view mechanism, multiple databases,
04-23
security, workflows, reusable components, etc.
a general-purpose web toolkit sitting on top of Django and others.
Django-hotsauce is an interactive Pythonic API to create scalable
Django- 2019-
0.9.8 web applications in Python. Currently providing native bindings
hotsauce 03-31
for the Schevo DBMS, Durus, ZODB, and Authkit projects.
Source code Documentation
a strict MVC framework that strictly separated Model, View and
Controller elements so that Designers, Web Developers, and
2013-
Giotto 0.10.5 Sysadmins can work independently of each other. Giotto includes
01-18
controller modules that allow applications to be built on top of the
web, irc or the command line.
built on the existing Zope 3 libraries, but aims to provide an
2018- easier learning curve and a more agile development experience. It
Grok 3.1
05-09 does this by placing an emphasis on convention over
configuration and DRY (Don't Repeat Yourself).
2010- a lightweight Web framework emphasizing flexibility and rapid
Pylons 1.0
05-28 development. It combines the very best ideas from the worlds of
Ruby, Python and Perl, providing a structured but extremely
flexible Python Web framework. It was also one of the first
projects to leverage the emerging WSGI standard, which allows
extensive re-use and flexibility but only if you need it. Out of the
box, Pylons aims to make Web development fast, flexible and
easy. Pylons is built on top of Paste (see below). NOTE: Pylons
the web framework is in maintenance-only status after merging
with Pyramid to form the Pylons Project to develop web
technologies using Python.
With Reahl, programming is done purely in Python, using
2018-
Reahl 4.0.5 concepts familiar from GUI programming - like reusable Widgets
12-11
and Events.
A full stack Python framework for building consumer and
business web applications. Websauna builds upon Pyramid,
2019- SQLAlchemy, and other mature open source components. Jupyter
Websauna 1.0a13
06-26 Notebook is directly integrated to Websauna. Analyzing website
data and building interactive visualizations is within a reach of
one click. Websauna needs Python 3.5.2 or newer.
A lightweight, high performance, high concurrency WSGI web
framework with the key features to build modern, efficient web.
Requires Python 2.4-2.7 or 3.2+. MVC architectural pattern
(push-based). Includes routing, model update/validation,
2015-
wheezy.web 0.1.485 authentication/authorization, content caching with dependency,
05-24
xsrf/resubmission protection, AJAX+JSON, i18n (gettext),
middlewares, and more. Template engine agnostic (integration
with: jinja2, mako, tenjin and wheezy template) plus html
widgets.
Being the grandaddy of Python web frameworks, Zope has grown
into a family of frameworks over the years. Zope 1 was released
in 1999. Zope 2 is both a web framework and a general purpose
2019- application server, today it is primarily used by
Zope2 4.0
05-10 ContentManagementSystems. Zope 3 is both a standalone
framework and a collection of related libraries, which are also
included with newer releases of Zope 2. All of the Zope
frameworks include the ZODB, an object database for Python.
Kiss.py (1.0.0 Released 2014-06-23) MVC web framework in Python with Gevent,
Jinja2, Werkzeug.
Lino (19.7.2 Released 2019-07-04), a framework for creating customized enterprise-level
Rich Internet Applications using Sencha ExtJS and Django.
Nagare (0.5.1 Released 2018-01-25) - a new approach for the rapid development of web
applications, thanks to advanced features like truely autonomous and reusable
components, continuation, programmatic HTML/XML, automatic AJAX rendering and
database ORM.
Pylatte (1.0 Released 2013-02-03) - Pylatte is Python3-based web framework. Pylatte is
used pyl code to make web site. pyl code is compose to python and HTML. so pyl code
seem like php code. easy to learn, easy to run.
Tipfy (1.0b3 Released 2011-07-18) tipfy is a small but powerful framework made
specifically for Google App Engine.
Tornado (6.0.3 Released 2019-06-23) is an open source version of the scalable, non-
blocking web server and and tools that power FriendFeed (acquired by Facebook with
this project released as open source).
watson-framework (3.5.2 Released 2018-01-15, initial release 2012-11-26) A component
based WSGI web framework giving you the tools needed to build your web apps quickly
and easily:
o Requires Python 3.3+.
o MVC based architecture
o Dependency injection
o Event driven
webapp2 (3.0.0b1 Released 2016-09-13) - a lightweight framework compatible with
Google App Engine’s webapp: it extends webapp to add better URI routing and
exception handling, a full featured response object and a more flexible dispatching
mechanism. Also offers sessions, localization, internationalization, domain and
subdomain routing and secure cookies. Can be used outside of App Engine,
independently of the App Engine SDK.
WebBot (0.5.0 Released 2013-04-10) - A QT inspired web framework that includes a
graphical interface builder, AJAX abstraction, and integration support for Google's
AppEngine.
WebCore (2.0.3 Released 2016-09-25) A full-stack, light-weight and efficient web
development framework. Web applications as simple as a single file, or as structured as
you want. Utilizes popular WSGI components, ORMs, etc. without locking you in, and
offers a unique init.d-like middleware configuration.
web.py (0.39 Released 2018-02-28) Think about the ideal way to write a Web app. Write
the code to make it happen.
Webware for Python (1.2.2 Released 2019-08-04) is a suite of Python packages and tools
for developing object-oriented, web-based applications.
Werkzeug (0.15.4 Released 2019-05-15) is Unicode-aware, includes a powerful
debugger, full featured request and response objects, HTTP utilities to handle entity tags,
cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL
routing system and a bunch of community contributed addon modules.
WHIFF (1.1 Released 2013-07-09) WHIFF is a collection of support services for
WSGI/Python web applications which allows applications to be composed by "dropping"
dynamic pages into container directories. It automatically includes support for advanced
features such as AJAX, jQueryUI widgets, Flash based charts and more. Extensive
documentation and tutorial essays.
Bottle (0.12.17 Released 2019-06-23) is a fast and simple micro-framework for small
web-applications. It offers request dispatching (Routes) with url parameter support,
Templates, key/value Databases, a build-in HTTP Server and adapters for many third
party WSGI/HTTP-server and template engines. All in a single file and with no
dependencies other than the Python Standard Library.
CherryPy (18.1.2 Released 2019-06-23) is a pythonic, object-oriented HTTP framework.
CherryPy powered web applications are in fact stand-alone Python applications
embedding their own multi-threaded web server. TurboGears, web2py (see above) also
use CherryPy.
Flask (1.0.2 Released 2018-05-02) is “a microframework for Python based on Werkzeug,
Jinja 2 and good intentions.” Includes a built-in development server, unit tesing support,
and is fully Unicode-enabled with RESTful request dispatching and WSGI compliance.
Hug (2.5.6 Released 2019-06-21) Embrace the APIs of the future. Hug aims to make
developing APIs as simple as possible, but no simpler. It's one of the first fully future
looking frameworks: only supporting Python3+.
Pyramid (1.10.4 Released 2019-04-15) a small, fast, down-to-earth, open source Python
web development framework. It makes real-world web application development and
deployment more fun, more predictable, and more productive. Pyramid is a Pylons
Project, and is the successor to the Pylons web framework.
References
https://wiki.python.org/moin/WebFrameworks
Django is a full-stack web framework, whereas Flask is a micro and lightweight web framework. ...
On the other hand, Flask accelerates development of simple web applications by providing the
required functionality. Hence, the developers must keep in mind the needs of individual projects
while comparing Flask and Django.
Is flask easier than Django?
Flask is more Pythonic than Django because the code of flask Web Application in most cases is
more explicit than the Django Web Application code. So it is easy for Python coders to pick up.
... So for smaller application Flask can give more performance. httpbin is a smaller application
built with Flask
https://docs.djangoproject.com/en/2.2/intro/tutorial01/
Django
Overview
Download
Documentation
News
Community
Code
Issues
About
♥ Donate
Documentation
Search:
Language: en
Throughout this tutorial, we’ll walk you through the creation of a basic poll application.
A public site that lets people view polls and vote in them.
An admin site that lets you add, change, and delete polls.
We’ll assume you have Django installed already. You can tell Django is installed and which
version by running the following command in a shell prompt (indicated by the $ prefix):
If Django is installed, you should see the version of your installation. If it isn’t, you’ll get an
error telling “No module named django”.
This tutorial is written for Django 2.2, which supports Python 3.5 and later. If the Django version
doesn’t match, you can refer to the tutorial for your version of Django by using the version
switcher at the bottom right corner of this page, or update Django to the newest version. If you’re
using an older version of Python, check What Python version can I use with Django? to find a
compatible version of Django.
See How to install Django for advice on how to remove older versions of Django and install a
newer one.
Creating a project¶
If this is your first time using Django, you’ll have to take care of some initial setup. Namely,
you’ll need to auto-generate some code that establishes a Django project – a collection of
settings for an instance of Django, including database configuration, Django-specific options and
application-specific settings.
From the command line, cd into a directory where you’d like to store your code, then run the
following command:
This will create a mysite directory in your current directory. If it didn’t work, see Problems
running django-admin.
Note
You’ll need to avoid naming projects after built-in Python or Django components. In particular,
this means you should avoid using names like django (which will conflict with Django itself) or
test (which conflicts with a built-in Python package).
If your background is in plain old PHP (with no use of modern frameworks), you’re probably
used to putting code under the Web server’s document root (in a place such as /var/www). With
Django, you don’t do that. It’s not a good idea to put any of this Python code within your Web
server’s document root, because it risks the possibility that people may be able to view your code
over the Web. That’s not good for security.
Put your code in some directory outside of the document root, such as /home/mycode.
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
You have unapplied migrations; your app may not work properly until they are
applied.
Run 'python manage.py migrate' to apply them.
Note
Ignore the warning about unapplied database migrations for now; we’ll deal with the database
shortly.
You’ve started the Django development server, a lightweight Web server written purely in
Python. We’ve included this with Django so you can develop things rapidly, without having to
deal with configuring a production server – such as Apache – until you’re ready for production.
Now’s a good time to note: don’t use this server in anything resembling a production
environment. It’s intended only for use while developing. (We’re in the business of making Web
frameworks, not Web servers.)
Now that the server’s running, visit http://127.0.0.1:8000/ with your Web browser. You’ll see a
“Congratulations!” page, with a rocket taking off. It worked!
By default, the runserver command starts the development server on the internal IP at port
8000.
If you want to change the server’s port, pass it as a command-line argument. For instance, this
command starts the server on port 8080:
If you want to change the server’s IP, pass it along with the port. For example, to listen on all
available public IPs (which is useful if you are running Vagrant or want to show off your work
on other computers on the network), use:
0 is a shortcut for 0.0.0.0. Full docs for the development server can be found in the runserver
reference.
The development server automatically reloads Python code for each request as needed. You
don’t need to restart the server for code changes to take effect. However, some actions like
adding files don’t trigger a restart, so you’ll have to restart the server in these cases.
Each application you write in Django consists of a Python package that follows a certain
convention. Django comes with a utility that automatically generates the basic directory structure
of an app, so you can focus on writing code rather than creating directories.
Your apps can live anywhere on your Python path. In this tutorial, we’ll create our poll app right
next to your manage.py file so that it can be imported as its own top-level module, rather than a
submodule of mysite.
To create your app, make sure you’re in the same directory as manage.py and type this
command:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
polls/views.py¶
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
This is the simplest view possible in Django. To call the view, we need to map it to a URL - and
for this we need a URLconf.
To create a URLconf in the polls directory, create a file called urls.py. Your app directory
should now look like:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
urls.py
views.py
polls/urls.py¶
urlpatterns = [
path('', views.index, name='index'),
]
The next step is to point the root URLconf at the polls.urls module. In mysite/urls.py, add
an import for django.urls.include and insert an include() in the urlpatterns list, so you
have:
mysite/urls.py¶
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
The include() function allows referencing other URLconfs. 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.
You should always use include() when you include other URL patterns. admin.site.urls is
the only exception to this.
You have now wired an index view into the URLconf. Verify it’s working with the following
command:
Go to http://localhost:8000/polls/ in your browser, and you should see the text “Hello, world.
You’re at the polls index.”, which you defined in the index view.
If you get an error page here, check that you’re going to http://localhost:8000/polls/ and not
http://localhost:8000/.
The path() function is passed four arguments, two required: route and view, and two optional:
kwargs, and name. At this point, it’s worth reviewing what these arguments are for.
route is a string that contains a URL pattern. When processing a request, Django starts at the
first pattern in urlpatterns and makes its way down the list, comparing the requested URL
against each pattern until it finds one that matches.
Patterns don’t search GET and POST parameters, or the domain name. For example, in a request
to https://www.example.com/myapp/, the URLconf will look for myapp/. In a request to
https://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.
When Django finds a matching pattern, it calls the specified view function with an HttpRequest
object as the first argument and any “captured” values from the route as keyword arguments.
We’ll give an example of this in a bit.
Arbitrary keyword arguments can be passed in a dictionary to the target view. We aren’t going to
use this feature of Django in the tutorial.
Naming your URL lets you refer to it unambiguously from elsewhere in Django, especially from
within templates. This powerful feature allows you to make global changes to the URL patterns
of your project while only touching a single file.
Writing your first Django app, part 2¶
This tutorial begins where Tutorial 1 left off. We’ll setup the database, create your first model,
and get a quick introduction to Django’s automatically-generated admin site.
Database setup¶
Now, open up mysite/settings.py. It’s a normal Python module with module-level variables
representing Django settings.
By default, the configuration uses SQLite. If you’re new to databases, or you’re just interested in
trying Django, this is the easiest choice. SQLite is included in Python, so you won’t need to
install anything else to support your database. When starting your first real project, however, you
may want to use a more scalable database like PostgreSQL, to avoid database-switching
headaches down the road.
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:
If you are not using SQLite as your database, additional settings such as USER, PASSWORD,
and HOST must be added. For more details, see the reference documentation for DATABASES.
If you’re using a database besides SQLite, make sure you’ve created a database by this point. Do
that with “CREATE DATABASE database_name;” within your database’s interactive prompt.
Also make sure that the database user provided in mysite/settings.py has “create database”
privileges. This allows automatic creation of a test database which will be needed in a later
tutorial.
If you’re using SQLite, you don’t need to create anything beforehand - the database file will be
created automatically when it is needed.
By default, INSTALLED_APPS contains the following apps, all of which come with Django:
These applications are included by default as a convenience for the common case.
Some of these applications make use of at least one database table, though, so we need to create
the tables in the database before we can use them. To do that, run the following command:
/
$ python manage.py migrate
The migrate command looks at the INSTALLED_APPS setting and creates any necessary
database tables according to the database settings in your mysite/settings.py file and the database
migrations shipped with the app (we’ll cover those later). You’ll see a message for each
migration it applies. If you’re interested, run the command-line client for your database and type
\dt (PostgreSQL), SHOW TABLES; (MySQL), .schema (SQLite), or SELECT
TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created.
Like we said above, the default applications are included for the common case, but not
everybody needs them. If you don’t need any or all of them, feel free to comment-out or delete
the appropriate line(s) from INSTALLED_APPS before running migrate. The migrate command
will only run migrations for apps in INSTALLED_APPS.
Creating models¶
Now we’ll define your models – essentially, your database layout, with additional metadata.
Philosophy
A model is the single, definitive source of truth about your data. It contains the essential fields
and behaviors of the data you’re storing. Django follows the DRY Principle. The goal is to
define your data model in one place and automatically derive things from it.
This includes the migrations - unlike in Ruby On Rails, for example, migrations are entirely
derived from your models file, and are essentially just a history that Django can roll through to
update your database schema to match your current models.
In our simple poll app, we’ll create two models: Question and Choice. A Question has a question
and a publication date. A Choice has two fields: the text of the choice and a vote tally. Each
Choice is associated with a Question.
These concepts are represented by simple Python classes. Edit the polls/models.py file so it looks
like this:
polls/models.py¶
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Each field is represented by an instance of a Field class – e.g., CharField for character fields and
DateTimeField for datetimes. This tells Django what type of data each field holds.
The name of each Field instance (e.g. question_text or pub_date) is the field’s name, in machine-
friendly format. You’ll use this value in your Python code, and your database will use it as the
column name.
You can use an optional first positional argument to a Field to designate a human-readable name.
That’s used in a couple of introspective parts of Django, and it doubles as documentation. If this
field isn’t provided, Django will use the machine-readable name. In this example, we’ve only
defined a human-readable name for Question.pub_date. For all other fields in this model, the
field’s machine-readable name will suffice as its human-readable name.
Some Field classes have required arguments. CharField, for example, requires that you give it a
max_length. That’s used not only in the database schema, but in validation, as we’ll soon see.
A Field can also have various optional arguments; in this case, we’ve set the default value of
votes to 0.
Finally, note a relationship is defined, using ForeignKey. That tells Django each Choice is
related to a single Question. Django supports all the common database relationships: many-to-
one, many-to-many, and one-to-one.
Activating models¶
That small bit of model code gives Django a lot of information. With it, Django is able to:
But first we need to tell our project that the polls app is installed.
Philosophy
Django apps are “pluggable”: You can use an app in multiple projects, and you can distribute
apps, because they don’t have to be tied to a given Django installation.
To include the app in our project, we need to add a reference to its configuration class in the
INSTALLED_APPS setting. The PollsConfig class is in the polls/apps.py file, so its dotted path
is 'polls.apps.PollsConfig'. Edit the mysite/settings.py file and add that dotted path to the
INSTALLED_APPS setting. It’ll look like this:
mysite/settings.py¶
INSTALLED_APPS = [
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Now Django knows to include the polls app. Let’s run another command:
/
$ python manage.py makemigrations polls
Migrations are how Django stores changes to your models (and thus your database schema) -
they’re just files on disk. You can read the migration for your new model if you like; it’s the file
polls/migrations/0001_initial.py. Don’t worry, you’re not expected to read them every time
Django makes one, but they’re designed to be human-editable in case you want to manually
tweak how Django changes things.
There’s a command that will run the migrations for you and manage your database schema
automatically - that’s called migrate, and we’ll come to it in a moment - but first, let’s see what
SQL that migration would run. The sqlmigrate command takes migration names and returns their
SQL:
/
$ python manage.py sqlmigrate polls 0001
You should see something similar to the following (we’ve reformatted it for readability):
BEGIN;
--
-- 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;
Note the following:
The exact output will vary depending on the database you are using. The example above
is generated for PostgreSQL.
Table names are automatically generated by combining the name of the app (polls) and
the lowercase name of the model – question and choice. (You can override this behavior.)
Primary keys (IDs) are added automatically. (You can override this, too.)
By convention, Django appends "_id" to the foreign key field name. (Yes, you can
override this, as well.)
The foreign key relationship is made explicit by a FOREIGN KEY constraint. Don’t
worry about the DEFERRABLE parts; that’s just telling PostgreSQL to not enforce the
foreign key until the end of the transaction.
It’s tailored to the database you’re using, so database-specific field types such as
auto_increment (MySQL), serial (PostgreSQL), or integer primary key autoincrement
(SQLite) are handled for you automatically. Same goes for the quoting of field names –
e.g., using double quotes or single quotes.
The sqlmigrate command doesn’t actually run the migration on your database - it just
prints it to the screen so that you can see what SQL Django thinks is required. It’s useful
for checking what Django is going to do or if you have database administrators who
require SQL scripts for changes.
If you’re interested, you can also run python manage.py check; this checks for any problems in
your project without making migrations or touching the database.
Now, run migrate again to create those model tables in your database:
/
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Rendering model states... DONE
Applying polls.0001_initial... OK
The migrate command takes all the migrations that haven’t been applied (Django tracks which
ones are applied using a special table in your database called django_migrations) and runs them
against your database - essentially, synchronizing the changes you made to your models with the
schema in the database.
Migrations are very powerful and let you change your models over time, as you develop your
project, without the need to delete your database or tables and make new ones - it specializes in
upgrading your database live, without losing data. We’ll cover them in more depth in a later part
of the tutorial, but for now, remember the three-step guide to making model changes:
Read the django-admin documentation for full information on what the manage.py utility can do.
/
$ python manage.py shell
We’re using this instead of simply typing “python”, because manage.py sets the
DJANGO_SETTINGS_MODULE environment variable, which gives Django the Python import
path to your mysite/settings.py file.
>>> from polls.models import Choice, Question # Import the model classes we
just wrote.
# Save the object into the database. You have to call save() explicitly.
>>> q.save()
Wait a minute. <Question: Question object (1)> isn’t a helpful representation of this object.
Let’s fix that by editing the Question model (in the polls/models.py file) and adding a __str__()
method to both Question and Choice:
polls/models.py¶
from django.db import models
class Question(models.Model):
# ...
def __str__(self):
return self.question_text
class Choice(models.Model):
# ...
def __str__(self):
return self.choice_text
It’s important to add __str__() 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
class Question(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
Note the addition of import datetime and from django.utils import timezone, to reference
Python’s standard datetime module and Django’s time-zone-related utilities in
django.utils.timezone, respectively. If you aren’t familiar with time zone handling in Python, you
can learn more in the time zone support docs.
Save these changes and start a new Python interactive shell by running python manage.py shell
again:
# 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 = Question.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
<QuerySet []>
For more information on model relations, see Accessing related objects. For more on how to use
double underscores to perform field lookups via the API, see Field lookups. For full details on
the database API, see our Database API reference.
Generating admin sites for your staff or clients to add, change, and delete content is tedious work
that doesn’t require much creativity. For that reason, Django entirely automates creation of
admin interfaces for models.
Django was written in a newsroom environment, with a very clear separation between “content
publishers” and the “public” site. Site managers use the system to add news stories, events,
sports scores, etc., and that content is displayed on the public site. Django solves the problem of
creating a unified interface for site administrators to edit content.
The admin isn’t intended to be used by site visitors. It’s for site managers.
First we’ll need to create a user who can login to the admin site. Run the following command:
/
$ python manage.py createsuperuser
Username: admin
Password: **********
Password (again): *********
Superuser created successfully.
The Django admin site is activated by default. Let’s start the development server and explore it.
/
$ python manage.py runserver
Now, open a Web browser and go to “/admin/” on your local domain – e.g.,
http://127.0.0.1:8000/admin/. You should see the admin’s login screen:
Since translation is turned on by default, the login screen may be displayed in your own
language, depending on your browser’s settings and if Django has a translation for this language.
Now, try logging in with the superuser account you created in the previous step. You should see
the Django admin index page:
You should see a few types of editable content: groups and users. They are provided by
django.contrib.auth, the authentication framework shipped by Django.
But where’s our poll app? It’s not displayed on the admin index page.
Just one thing to do: we need to tell the admin that Question objects have an admin interface. To
do this, open the polls/admin.py file, and edit it to look like this:
polls/admin.py¶
from django.contrib import admin
admin.site.register(Question)
Now that we’ve registered Question, Django knows that it should be displayed on the admin
index page:
Click “Questions”. Now you’re at the “change list” page for questions. This page displays all the
questions in the database and lets you choose one to change it. There’s the “What’s up?”
question we created earlier:
Save – Saves changes and returns to the change-list page for this type of object.
Save and continue editing – Saves changes and reloads the admin page for this object.
Save and add another – Saves changes and loads a new, blank form for this type of
object.
Delete – Displays a delete confirmation page.
If the value of “Date published” doesn’t match the time when you created the question in
Tutorial 1, it probably means you forgot to set the correct value for the TIME_ZONE setting.
Change it, reload the page and check that the correct value appears.
Change the “Date published” by clicking the “Today” and “Now” shortcuts. Then click “Save
and continue editing.” Then click “History” in the upper right. You’ll see a page listing all
changes made to this object via the Django admin, with the timestamp and username of the
person who made the change:
More Information….. click onto the following link
https://docs.djangoproject.com/en/2.2/intro