[Python] using Django for web development

Source: Internet
Author: User
Tags django website install django server port

First step: Download and install Django

First, download the Django version of Python for yourself on the Django website and make sure you've successfully installed Python before you install Django.

Installing Django under Windows system:

  Unzip the downloaded Django package, locate the setup.py file, and then open the CMD Command window and execute the following command in its corresponding path:

Python setup.py Install

  Installing Django under a Linux system:

  Enter the following command in the shell:

$ tar xzvf django-*. tar.gz$ CD django-*$ sudo python setup.py install 

  Confirm that the Django installation is successful:

  Under the Python IDE, enter:

Import Djangodjango. VERSION

  If you see the Django version information, it means the installation was successful.

Step two: Run the server.

First, start creating a new project first.

  Locate your django-admin.py file and add it to the system path. If the setup.py tool is installed, the django,django-admin.py should have been added to the system path. My django-admin.py directory is C:\Python27\Lib\site-packages\Django-1.11.5-py2.7.egg\django\bin.

Enter this directory and run the following command to create a new project:

Python django-admin.py startproject MySite

  The startproject command creates a directory that contains a folder named MySite and a file named manage.py. Where the MySite folder contains four files, respectively:

  __init__.py

settings.py

urls.py

wsgi.py

  For more experience after installation, let's run the Django Development server to see our quasi-system. The Django Development Service is available during development, a built-in, lightweight Web service. We provide this server to allow you to develop your site quickly, meaning that there is no need to configure a product-level WEB server (such as Apache) before you are ready to release your product. The development server monitors your code and loads it automatically, so you can easily modify the code without restarting the service. If you have not started the server, please switch to your project directory (CD MySite) and run the following command:

Python manage.py runserver

  You'll see something like this:

Django version 1.11.5, using Settings ' mysite.settings ' starting development server at Http://127.0.0.1:8000/Quit the SER Ver with Ctrl-break

 This will start a local server on port 8000 and can only be connected and accessed from your computer. Now that the server is up and running, use a Web browser to access Http://127.0.0.1:8000/. You should be able to see a pleasing light blue Django Welcome page. It's starting to work.

  The interface looks like this:

Note: Although the Web server that Django comes with is convenient for development, never use it in a formal application deployment environment. At the same time, the server can only reliably process a single request and does not perform any type of security audit.

  Change the host address or port of the development Server. By default, the Runserver command starts the development server on port 8000 and listens only for local connections. To change the server port, you can pass the port as a command line parameter:

Python manage.py runserver 8080

By specifying an IP address, you can tell the server – Allow non-local connection access. This feature is especially useful if you want to share the same development site with other developers. "0.0.0.0" This IP address, tells the server to listen to any network interface.

Python manage.py runserver 0.0.0.0:8000

  When these settings are complete, the other computers on your local network will be able to access your IP address in your browser. For example: Http://192.168.1.103:8000/. (Note that you will need to inspections your network configuration to determine your IP address on the local network) UNIX users can enter ifconfig at the command prompt to obtain the above information. For users who use Windows, try the ipconfig command.

Step three: Create a view file.

Before writing the first page, we will first create a file named views.py in the MySite directory. Of course, naming is not required, you can also be named a.py,b.py ... Name it according to your preference. Write the following code in the created views.py, and Save:

Import httpresponsedef Hello (request):    return HttpResponse ("")    

  Analyze This code line by row:

First, we import the HttpResponse class from the Django.http module.

Next, we define a view function called Hello. Each view function must have at least one parameter, which is often called a request. This is an object that triggers this view, contains the current Web request information, and is an instance of the class Django.http.HttpResponse. In this example, although we don't have to do anything with the request, it still has to be the first parameter of the view. Note that the name of the view function is not important, and it does not necessarily have to be named in a particular way for Django to recognize it. Here we name it: Hello, because the name clearly shows the purpose of the view. In the same way, you can name it with an ugly short phrase such as: Hello_wonderful_beautiful_world.

This function has a simple line of code: it simply returns a HttpResponse object that contains the text "Hello World".

Here's what to keep in mind: A view is a function of Python. The type of the first parameter of this function is HttpRequest; it returns a HttpResponse instance. In order for a Python function to be a Django-aware view, it must satisfy both of these conditions.  

Fourth step: Configure the URL.

Now, if you run again: Python manage.py runserver, you'll also see the Django Welcome page without seeing the Hello World display page we just wrote. That's because our MySite project also knows nothing about the Hello view. We need to explicitly tell it and activate this view through a URL that is described in detail. To bind the view functions and URLs, we use urlconf, the urls.py file. 

  URLconf is like a directory of Django-supported websites. Its essence is the URL pattern and the mapping table between the view functions to invoke for that URL pattern. That's how you tell Django to call that code for that URL and call that code for that URL. For example, when a user accesses/foo/, the View function Foo_view () is called, and this view function exists in the Python module file view.py.

  If you want to add URLs and view to urlconf, simply add the python tuple that maps the URL pattern and view functionality. Here's how to add the Hello feature in view.

 from django.conf.urls  import url  
from django.contrib import admin from mysite.views import Hellourlpatterns = [
url (R ' ^admin/', admin.site.urls), URL ( r ' ^hello / "]

  Let's analyze this code on a row-by-line basis:

  First, we introduced the Hello View from the module.

  Next, we add a line to Urlpatterns: The URL (' ^hello/$ ', hello), which is called the Urlpattern, which is a python tuple. The first element in a tuple is a pattern-matching string (a regular expression), and the second element is the view function that the pattern will use.  The Urlpattern contains a caret (^) and a dollar sign ($). These are regular expression symbols and have a specific meaning: The up arrow requires the expression to match the head of the string, and the dollar sign requires the expression to match the tail of the string.  In short, this code simply tells Django that all requests to url:/hello/should be handled by the Hello view function. Fifth Step: Verify. Start the Django Development server to test the modified URLconf, run command line pythonmanage.py runserver. The address of the development server is Http://127.0.0.1:8000/, which opens your browser to access http://127.0.0.1:8000/hello/. You can see the output. The development server will automatically detect changes to Python code to do the necessary reloading, so you do not need to restart the server after the code changes. The server runs the address "http://127.0.0.1:8000/", so open the browser directly into "http://127.0.0.1:8000/hello/" and you will see the output page by your Django view as shown below:

 To summarize:

    1. The incoming request was transferred to/hello/.

    1. Django determines the root urlconf by root_urlconf configuration.

    1. Django finds the first entry that matches the/hello/in all the URL patterns in urlconf.

    1. If a match is found, the corresponding view function is called.

    1. The view function returns a HttpResponse.

    1. The Django Transform HttpResponse is a suitable HTTP response that is displayed as a Web page.

  In fact, to make a django-powered page, just write the view function and use Urlconfs to match them with the URLs are OK.

Sixth step: Write a dynamic page.

Our Hello world view is used to demonstrate how basic Django works, but it is not an example of a dynamic Web page, because the content of the page is always the same. Each time you go to view/hello/, you will see the same content, which resembles a static HTML file. In the second example, the blogger simply demonstrates a dynamic page with a page showing the current time. Dynamic pages are written in the same way as static pages, with two parts: creating views and configuring URLs.

  The view file views.py code is as follows:

Import httpresponseimport timedefreturn HttpResponse ("" +time.strftime ('%y- %m-%d%h:%m:%s'))         

  The urlconf file urls.py code is as follows:

FromDjango.conf.urls ImportURL
from django.contrib import admin
From mysite.views import Hello From mysite.views import current_timeurlpatterns = [
URL (R ' ^admin/', admin.site.urls),
URL (r ' ^hello/', hello), URL (r '^current_time/', current_time),
]

  Then we can see the first dynamic page written by the URL http://127.0.0.1:8000/current_time/, which shows the current time when you visit the page, as shown in the following:

[Python] uses Django for web development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.