English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django Quick Start

Quick Installation

Before using Django, we need to install it first. We have a complete installation guide that covers all possibilities; this guide will guide you through a simple, minimalist installation.

Windows Installation Reference: https://docs.djangoproject.com/en/1.9/howto/windows/

Install Python

As a Python Web framework, Django requires support from the Python environment. Python includes a lightweight database: SQLite, so we will not need to set up a database.

Get the latest version of Python at the following URL: https://www.python.org/download/ Or choose the software package manager corresponding to your operating system.

You can verify that Python is installed by typing python; in the shell; you should see an output similar to this:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
Python 3.4.x
 [GCC 4.x] on Linux
 Type "help", "copyright", "credits", or "license" for more information.
 >>>

Configure the database

If you want to work with a 'big' database engine like PostgreSQL, MySQL, and Oracle, please refer to Database installation information.

Delete all old versions of Django

If you are upgrading to install Django from an old version or other aspects, you need Uninstall the old version of Django before installing a new version.

Install Django

Generally, three simple options are used to install Django:

Install byA Django version provided by the operating system distribution. This is the fastest choice for those who distribute Django to their operating systems.

Install  Official release version. This is the best method for most users.

Install the latest development version. This option is for enthusiasts who want the latest and are not afraid of bugs in new code. You may encounter bugs in developing new versions and report them to help the development of Django. In addition, third-party software package versions are unlikely to be compatible with the latest stable version in the development version.

Install Windows

We assume that your Django archive and Python are installed on the computer, and the current latest version is:1.9.1, you can download it through the following URL: https://www.djangoproject.com/download/

First, path verification.

In some versions of Windows (Windows 7) to ensure that the Path system variable path is as follows: C:\Python27\;C:\Python27\Lib\site-packages\django\bin\, of course, this depends on your Python version.

Then, extract and install Django, here we decompress it to C:\Python27\

Next, by running the following command, you may need administrative privileges in the Windows shell 'cmd' to install Django −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
', monospace;line-height:1.5">C:\Python27\Django-1.9.1
  >>> python setup.py install

To test your installation, open the command prompt, enter Python from the shell to see. Then at the Python prompt, try to import Django:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
>>> import django
 >>> print(django.get_version())
 1.9.1

This is the end of the installation. Next, we will enter the first step of development.


Developing the first Django app

Let's start creating a web application and learn step by step.

In this tutorial, we will guide you through creating a basic survey (poll) application.

This will include two parts:

A public website where people can view and vote on polls.

A website management, where you can add, change, and delete votes.

Assuming your Django has been installed. You can confirm the Django installation and version by running the following command:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
$ python -c "import django; print(django.get_version())"

If you install Django, you should see the installed version. If it has not been installed, you will receive an error message: 'No module named django'.

This tutorial is using Django1.9and Python2.7and higher versions written. If the version of Django does not match, you can switch Django versions using version switching, or update Django to the latest version. If you are still using Python2.7If you need to adjust the code slightly, as described in the comments.

Create a project

If you are using Django for the first time, you must make some initial settings. That is, you need to automatically generate some code and establish a Django project - Set the collection of Django instances, including database configuration, Django-specific options, and specific application settings.

In the command line, cd to the directory where you want to store the code, for example, here I created the project at: C:\Python7\, then run the following command:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08C:\python27> django-admin startproject mysite

This will be in C:\python17Create the mysite directory under it. As shown in the following figure:

Let's take a look at the directory structure created by the startproject command:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
mysite/
     manage.py
     mysite/
         __init__.py
         settings.py
         urls.py
         wsgi.py

A brief description of the above files:

In mysite/ The parent directory is simply a container project. For Django, the name is arbitrary, and it can be renamed to anything you like.

manage.py: A command-line tool that allows you to interact with your Django project in various ways. You can read all about manage.py in django-Details of admin and manage.py. Internal mysite/The directory is the actual Python package of the project. Its name is the name you need to use to import any Python package within it (e.g., mysite.urls). mysite/__init__.py: An empty file that tells Python this directory should be treated as a Python package. mysite/settings.py: Settings/Configure this Django project. Django's settings will tell you how to set up the work. mysite/urls.py: The URL declarations for this Django project; akin to the 'content table' of a Django website. mysite/wsgi.py: An entry point for a WSGI-compliant web server to meet your project needs.

Development server

Let's verify your Django project. Change to the external 'mysite' directory, and if you are ready, run the following command:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08C:\python27\mysite> python manage.py runserver

You will see the output below the command line:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
Performing system checks...
 System check identified no issues (0 silenced).
 You have unapplied migrations; your app may not work properly until they are applied.
 Run 'python manage.py migrate' to apply them.
 January 24, 2016 - 15:50:53
 Django version 1.9, using settings 'mysite.settings'
 Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

You have started the Django development server, which is a lightweight web server written in Python. It is already included in Django, so you can develop things quickly without having to deal with configuring a production server - For example: Apache .

It should be noted that this server should not be used in any environment similar to a production environment. Its purpose is solely for development (we are using a web framework, not the business of a web server.).

Now that the server is running, please access it using a web browser: http://127.0.0.1:8000/. You will see a 'Welcome to Django' page. This indicates that it has been successfully installed!

By default, the runserver command starts the internal IP development server on the port 8000.

If you want to change the server's port, pass it as a command-line argument. For example, the following command will run the server808Run on port 0:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
$ python manage.py runserver 8080

If you want to change the server's IP, pass it to the port. (If you want to expose it on other computers or networks) all public IPs listen, use the following method:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
$ python manage.py runserver 0.0.0.0:8000

Create Polls app

The current 'project' - After the settings are completed, you can start working.

Each application written in Django contains a Python package, following certain conventions. Django provides a utility that automatically generates the basic directory structure of an application, allowing you to focus on writing code rather than building directories.

Applications can be located anywhere in the Python path. In this tutorial, we will create the voting program in the same directory as manage.py so that it can be imported as its own top-level module rather than a sub-module of mysite.

Before creating the application, make sure you are in the same directory as manage.py and type the following command:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08C:\python27\mysite> python manage.py startapp polls

This will create a directory 'polls', and the directory structure is as follows:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
polls/
     __init__.py
     admin.py
     apps.py
     migrations/
         __init__.py
     models.py
     tests.py
     views.py

This directory structure contains the 'poll' application.

Write the view code

Now let's write the first view. Open the file polls/views.py, put the following Python code inside it:


polls/urls.py
  # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import url, from . import views
 urlpatterns = [
     url(r'^, views.index, name='index'),
 ], views
    .index, name
    =
    'index'),
    
 ]

The next step is to have the polls.urls module point to the ROOT_URLCONF. In mysite/urls.py, add the import django.conf.urls.include and insert include() in the URL pattern list, so here it is:

<div fira="" mono',="" consolas,="" menlo,="" monaco,="" 'courier="" new'="" ,="" courier,="" monospace;"="">mysite/urls.py
  # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import include, url from django.contrib import admin
 urlpatterns = [
     url(r'^polls/', include('polls.urls')),
     url(r'^admin/', admin.site.urls),
 ]

Now we have connected the index view to the URL configuration. Let's verify the result by running the following command:

  # Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
', 'lucida sans', line-height:1.5">C:\Python27\mysite> python manage.py runserver

 

Open http: in the browser//localhost:8000/polls/, you should see the following text displayed: 'Hello, world. You’re at the polls index.' defined in the index view.

 

The url() function passes four parameters, two required: regex and view, and two optional: kwargs and name.

url() Parameter: regex

The term 'regex' is a common abbreviation, meaning 'regular expression', which is a string matching pattern syntax, or in our example, a URL pattern. Django starts with the first regular expression and makes it traverse the list, comparing each regular expression's requested URL until it finds a match.

Please note that these regular expressions do not search for GET and POST parameters, or domain names. For example, in a request https://www.example.com/myapp/, the URLconf will look for myapp/.In a request https://www.example.com/myapp/?page=3, the URLconf will also look for myapp/.

If you need help with regular expressions, please see the Wikipedia entry and    re Module documentation. However, in practice, you do not need to be an expert in regular expressions because you only need to know how to capture simple patterns. In fact, complex regular expressions can be slower in performance, so you may not rely on all the features of regular expressions.

Finally, one thing about performance needs to be understood: these regular expressions are compiled when the URL configuration module is loaded for the first time. They are super fast (as long as the search is not too complex - As described above).

url() Parameter: view

When Django finds a regular expression match, Django calls the specified view function, using the HTTP request object as the first parameter, and the other parameters 'captured' from the regular expression as its values. Regular expressions use simple capturing, and value passing is through positional parameters; if named captures are used, value passing is through keyword parameters. We will give an example.

url() Parameter: kwargs

Any keyword arguments can be passed through the target view in the dictionary. In this tutorial, we do not intend to use this feature of Django.

url() argument: name

Named URLs can refer to it, clearly distinguishing from other places in Django - Especially the template. This powerful feature allows you to make global changes to the project's URL patterns with just one file modification. Next, we will learn how to use data features in Django. Quick Start Series Tutorials:

Django Quick Start-Database Model  
  Django Quick Start-View  
  Django Quick Start-Form