Django creates the first project
In this chapter we will introduce the Django management tools and how to use Django to create the project, the first project we use HelloWorld to order the project.
Test Release Notes:
Django management tools
After installing Django, you should now have the available administrative tools django-admin.py. We can use django-admin.py to create a project:
We can look at the following django-admin.py command description:
Create the first project
Use django-admin.py to create a HelloWorld project
After the creation is complete, we can view the directory structure of the next project:
HelloWorld: container of the project.
Manage.py: A useful command-line tool that allows you to interact with the Django project in a variety of ways.
HelloWorld / __ init__.py: An empty file that tells Python that the directory is a Python package.
HelloWorld / settings.py: The settings / configuration of the Django project.
HelloWorld / urls.py: the Django project URL declaration; a Django-driven site “directory”.
HelloWorld / wsgi.py: A WSGI-compliant Web server portal to run your project.
Next we enter the HelloWorld directory and enter the following command to start the server:
0.0.0.0 to other computers can be connected to the development server, 8000 for the port number. If not, then the port number defaults to 8000.
In the browser input your server ip and port number, if the normal start, the output is as follows:
View and URL configuration
Create a new view.py file in the HelloWorld directory under the previously created HelloWorld directory and enter the code:
HelloWorld / HelloWorld / view.py file code:
Next, bind the URL with the view function. Open the urls.py file, delete the original code, copy and paste the following code into the urls.py file:
HelloWorld / HelloWorld / urls.py File Code:
The entire directory structure is as follows:
| |– __init__.py
| |– __init__.pyc
| |– settings.py
| |– settings.pyc
| |– urls.py # url deploy
| |– urls.pyc
| |– view.py # Added view file
| |– view.pyc # Compiled view file
| |– wsgi.py
| `– wsgi.pyc
We can also modify the following rules:
HelloWorld/HelloWorld/urls.py File code:
Through the browser to open http://127.0.0.1:8000/hello, the output is as follows
Note: If the code changes in the project, the server will automatically monitor the code changes and automatically reload, so if you have started the server without a manual restart.
Url () function
Django url () can receive four parameters, are two mandatory parameters: regex, view and two optional parameters: kwargs, name, then the details of these four parameters.
Regex: regular expression, matching the URL will perform the corresponding second parameter view.
View: Used to execute a URL request that matches a regular expression.
Kwargs: parameters of the dictionary type used by the view.
Name: used to reverse the URL.